Main Content

rlFunctionVectorEnv

R2026b

Create a vectorized reinforcement learning environment using your setup, reset, and step functions

Since R2026b

    Description

    Use rlFunctionVectorEnv to create a custom vectorized reinforcement learning environment by supplying your own step, reset, and setup MATLAB® functions. Vectorized environments use built-in vectorization features to step and reset many environment instances in batch. This capability can improve hardware utilization and enable higher data throughput compared to non-vectorized (that is, single-instance, or scalar) environments. For agents that use large experience batches, training against a vectorized environment can be much faster than training against a corresponding scalar version of the environment. After creating the environment, call validateEnvironment to check that the environment is configured correctly.

    venv = rlFunctionVectorEnv(observationInfo,actionInfo,stepFcn,resetFcn,setupFcn) creates a vectorized reinforcement learning environment using the observation specifications observationInfo and the action specification actionInfo, for one environment instance. The stepFcn, resetFcn, and setupFcn arguments are function handles to your step, reset, and setup MATLAB functions.

    venv = rlFunctionVectorEnv(observationInfo,actionInfo,stepFcn,resetFcn,setupFcn,NumEnv=N) also specifies the number of environment instances to create.

    example

    Examples

    collapse all

    In this example you create a vectorized reinforcement learning environment by specifying your custom step, reset, and setup MATLAB® functions.

    For this example, create a vectorized environment that represents a discrete-time double-integrator system with a continuous action space. A scalar version of this environment is available as a predefined environment. For more information, see Use Predefined Control System Environments.

    The observations from the environment are the position and velocity of a point along a line. Create an observation specification for these signals.

    obsInfo = rlNumericSpec([2 1]);

    The environment has a continuous action space where the agent can apply an acceleration value in the range [-1, 1] to the point. Create the action specification for this action.

    actInfo = rlNumericSpec([1 1]);
    actInfo.UpperLimit =  1;
    actInfo.LowerLimit = -1;

    Next, specify the setup, step, and reset functions. Unlike rlFunctionEnv, which requires only step and reset functions, rlFunctionVectorEnv also requires a setup function that initializes the environment data (typically the environment states and parameters). This data is shared across all environment instances. For this example, use the supplied functions vec_dblint_setupfcn.m, vec_dblint_resetfcn.m, and vec_dblint_stepfcn.m.

    Setup Function

    The setup function receives a structure containing a NumEnv field and returns an env_data structure that holds the state and parameters for NumEnv environment instances. For this example, vec_dblint_setup.m initializes a state matrix of size with two rows (position and velocity) and NumEnv columns (each column corresponds to a different environment instance). The function also stores the sampling time as a parameter.

    Display the setup function.

    type("vec_dblint_setupfcn.m")
    function env_data = vec_dblint_setupfcn(info)
    
    % Vectorized setup function for a double-integrator environment. 
    % This function initializes env_data.
    
    % Create matrix of initial states.
    env_data.x = zeros(2, info.NumEnv);
    
    % Store the sample time as parameter.
    env_data.Ts = 0.1;
    

    Reset Function

    The reset function receives both the env_data structure and a logical vector resetidx. The function then resets only the environments indicated by resetidx, and returns as outputs both the observation for the environments that were reset, and the updated env_data. In this function, you use matrix operations so that environment instances can be reset simultaneously.

    Display the reset function.

    type("vec_dblint_resetfcn.m")
    function [obs, env_data] = vec_dblint_resetfcn(env_data, resetidx)
    
    % Vectorized reset function for a double-integrator environment. 
    % This function resets the environment instances corresponding to the
    % true elements of resetidx.
    
    % Number of environment instances to reset.
    num_reset_env = nnz(resetidx);
    
    % Create vector of random numbers from -0.5 to 0.5 excluding zero.
    r = rand(1,num_reset_env) - 0.5;
    r(r == 0) = 1;
    
    % Reset state for indicated instances.
    % Set initial positions randomly to +4 or -4 and initial velocities to 0.
    env_data.x(1, resetidx) = 4.*sign(r);
    env_data.x(2, resetidx) = 0;
    
    % Assign initial observation for the indicated instances.  
    obs{1} = env_data.x(:, resetidx);
    

    Step Function

    The step function receives the env_data structure and a cell array of actions. The function returns observations, rewards, an is-done flag vector, and the updated env_data. In this function, you write the dynamics in a fully vectorized fashion so that all environment instances can be stepped simultaneously.

    Display the step function.

    type("vec_dblint_stepfcn.m")
    function [obs, rwd, isd, env_data] = vec_dblint_stepfcn(env_data, act)
    
    % Vectorized step function for a double-integrator environment. 
    % Write the dynamics in matrix form to take advantage of vectorization.
    
    % State and input matrices representing a double integrator system.
    a = [0,1;0 0];
    b = [0;1];
    
    % The number of environments is the batch dimension of the action.
    % The batch dimension is the dimension following the last specification
    % dimension.
    num_env = size(act{1}, 3);
    
    % Extract the action and limit it between -1 and 1.
    u = max(min(act{1}(:,:),1),-1);
    
    % Extract the state matrix (2 by NumEnv) and the sample time.
    x = env_data.x;
    Ts = env_data.Ts;
    
    % Update the state for all environment instances using the Euler method.
    x = x + Ts.*(a*x + b*u);
    
    % Set the next observation value.
    obs{1} = x;
    
    % Calculate reward for all environment instances (1 by NumEnv).
    rwd = 1./(abs(x(1,:)) + 1);
    
    % Set the isdone vector (1 by NumEnv) to zero.
    isd = uint8(zeros(1, num_env));
    
    % Store the updated state (2 by NumEnv).
    env_data.x = x;
    

    Create the custom vectorized environment using the defined observation and action specifications, the function handles, and the desired number of parallel environment instances to create. Here, 128 environment instances are created.

    venv = rlFunctionVectorEnv(obsInfo,actInfo,...
    @vec_dblint_stepfcn,...
    @vec_dblint_resetfcn,...
    @vec_dblint_setupfcn,...
    NumEnv=128)
    venv = 
      rlVectorEnv with properties:
    
        NumEnv: 128
    
    

    Use validateEnvironment to validate the environment.

    validateEnvironment(venv)

    This function does not result in any error, so the environment is valid.

    You can now create an agent for venv and train or simulate it as you would for any other environment. Because the vectorized environment steps all instances at the same time, training with algorithms that benefit from large batches of experience can be significantly faster.

    Input Arguments

    collapse all

    Observation specifications for one environment instance, specified as an rlFiniteSetSpec or rlNumericSpec object or as an array containing any combination of such objects. Each element in the array defines the properties of an environment observation channel, such as its dimensions, data type, and name.

    Example: [rlNumericSpec([2 1]) rlFiniteSetSpec([3,5,7])]

    Action specification for a single environment instance, specified as one of the following:

    The action specification defines the properties of an environment action channel, such as its dimensions, data type, and name.

    Example: rlNumericSpec([1 1])

    Vectorized environment step function, specified as a function handle. The sim and train functions call StepFcn to update the environment at each simulation or training step.

    This function must have two inputs and four outputs, as illustrated by the following signature.

    [NextObservation,Reward,IsDone,EnvData] = myStepFunction(EnvData,Action)

    For a given environment data variable and a batch of action inputs, the step function must return the correspondent batch of values for: next observation, reward, and is-done (an uint8 value indicating whether the episode is terminated). The last output argument is the updated environment data.

    Specifically, the required input and output arguments are as follows.

    • EnvData — Any environment data that you want to pass from one step to the next. This can be the environment state or a structure containing state and parameters. Your step function takes this data as the first input argument, updates it according to your need (typically it updates the environment states), and returns the updated version as output.

      The simulation or training functions (train or sim) handle this variable by following these steps:

      1. Creating EnvData, using the second output argument returned by your SetupFcn, before starting the simulation or training.

      2. Initializing EnvData, using the second output argument returned by your ResetFcn, at the beginning of the episode.

      3. Passing EnvData, as first input argument to your StepFcn at the beginning of each training or simulation step.

      4. Updating EnvData, using the fourth output argument returned by your StepFcn at the end of each training or simulation step.

    • Action — Batch of current actions from the agent, with first dimensions as specified in actionInfo. The last dimension of the Action array, that is the batch dimension, is equal to the value of the NumEnv property of venv.

    • NextObservation — Batch of next observations. These are the observations generated by the transitions, caused by each element in Action, from the current environment state to the next one. The returned value must have the first dimensions as specified in observationInfo. The batch dimension is consistent with the batch dimension of Action and equal to the value of the NumEnv property of venv.

    • Reward — Batch of rewards generated by the transition, caused by each Action element, from the current state to the next one. This output must be a row vector with length consistent with the batch dimension of Action and equal to the value of the NumEnv property of venv.

    • IsDone — Batch of uint8 values,each one indicating whether to end the simulation or training episode following the corresponding action value in the Action array. This output must be a row vector with length consistent with the batch dimension of Action and equal to the value of the NumEnv property of venv.

    For an example showing how to pass more than two input arguments to the step function, see Create Custom Environment Using Step and Reset Functions.

    Example: @myStepFcn

    Vectorized environment reset function, specified as a function handle. The simulation or training functions call your reset function at the start of each episode.

    A typically reset function randomizes certain state and parameter values such that each training episode begins from different initial conditions.

    The reset function must have two inputs and two outputs, as illustrated by the following signature.

    [InitialObservation,EnvData] = myResetFunction(EnvData,resetidx)

    The function takes as inputs the environment data, which comes from your setup function, and the indices of the environments to reset. It then sets these environments to an initial state and computes the initial value of their observations.

    Specifically, the required input and output arguments are as follows.

    • EnvData — Any environment data (state and parameters) that you want to pass from one step to the next, as described in stepFcn. The reset function takes this data as first input argument, resets the environment instances specified by the resetidx argument, and returns the updated version as output.

    • resetidx — Logical array of length equal to the value of the NumEnv property of venv. Each true element of the array indicates that the corresponding environment in the batch needs to be reset.

    • InitialObservation — Batch of initial observations. The first dimensions of the returned value must match the dimensions specified in observationInfo. The batch dimension must be equal to the value of the NumEnv property of venv.

    For an example showing how to pass more than two arguments to the reset function, see Create Custom Environment Using Step and Reset Functions.

    Example: @myResetFcn

    Vectorized environment setup function, specified as a function handle. The simulation or training functions call your setup function to initialize the environment data variable before the start of each simulation or training episode.

    The setup function must have one input and one output, as illustrated by the following signature.

    EnvData = mySetupFunction(SetupInfo)

    SetupInfo is a structure that contains:

    • NumEnv — The number of environment instances.

    • ObservationInfo — The observation specification.

    • ActionInfo — The action specification.

    The setup function uses the information in SetupInfo to create an initial EnvData variable. EnvData contains the environment state and parameters that you want to pass from one step to the next, as described in stepFcn.

    Example: @mySetupFcn

    Number of environment instances, specified as a positive integer. This argument sets the NumEnv property of venv. If you omit this argument, the function uses the default value of 2.

    Example: NumEnv=128

    Output Arguments

    collapse all

    Vectorized environment, returned as a rlVectorEnv object.

    Version History

    Introduced in R2026b