Main Content

sim

Run and script programmatic simulations of Simulink models

Description

Simulink.SimulationInput Object Syntax

example

simout = sim(simin) runs one or more simulations of a Simulink® model according to the properties defined on one or more Simulink.SimulationInput objects.

  • If simin is a scalar Simulink.SimulationInput object, then simout is a scalar Simulink.SimulationOutput object.

  • If simin is a vector, matrix, or array of Simulink.SimulationInput objects, then simout is a vector, matrix, or array of Simulink.SimulationOutput objects with the same dimensions as simin.

You can use a SimulationInput object to configure options and inputs for simulations, including:

  • The model to simulate

  • Source variables or files for external input data

  • Block parameter values to use for the simulation

  • Model configuration parameter values to use for the simulation

When a property of the SimulationInput object modifies a model or block parameter value, the value is modified during simulation and reverted at the end of the simulation.

When you configure programmatic simulations using SimulationInput objects, you can easily transition from using the sim function to using other functions, such as parsim and batchsim.

For more information, see Run Simulations Programmatically.

simout = sim(simin,Name=Value) simulates a model according to the properties defined on the Simulink.SimulationInput object simin with additional options specified using one or more name-value arguments.

For a list of name-value arguments supported for the Simulink.SimulationInput syntax, see Simulink.SimulationInput Object Syntax.

Model Syntax

example

simout = sim(mdl) simulates the model mdl using the current configuration parameter and block parameter values for the model.

simout = sim(mdl,Name=Value) simulates the model mdl with options specified using one or more name-value arguments. For example, you can modify a model configuration parameter value for the simulation by specifying the parameter name and value as a name-value argument.

When you modify model configuration parameters by providing inputs to the sim function, the changes are applied during simulation and reverted at the end of the simulation.

For a list of name-value arguments supported for the model syntax, see Model Syntax.

example

simout = sim(mdl,paramstruct) simulates the model mdl using the model configuration parameter values specified by the structure paramstruct.

example

simout = sim(mdl,configset) simulates the model mdl using model configuration parameter values in the configuration set configset.

Examples

collapse all

You can use a Simulink.SimulationInput object to store the configuration for a simulation separate from the model you simulate. The configuration in the Simulink.SimulationInput object is applied to the model for the simulation. After simulation, any model settings that were changed revert to the original value.

Open the model IntegrateSine. The model uses an Integrator block to integrate the output of a Sine Wave block. The output from the Integrator block is connected to an Outport block.

The model IntegrateSine.

mdl = "IntegrateSine";
open_system(mdl)

Create a Simulink.SimulationInput object to store a simulation configuration for the model IntegrateSine.

simIn = Simulink.SimulationInput(mdl);

Use the setModelParameter function to configure the SimulationInput object to use the ode45 solver and to simulate to a stop time of 20 seconds.

simIn = setModelParameter(simIn,"Solver","ode45",...
    "StopTime","20");

Use the setBlockParameter function to configure the SimulationInput object to set the Amplitude parameter of the Sine Wave block to 2.

blk = strcat(mdl,"/Sine Wave");
simIn = setBlockParameter(simIn,blk,"Amplitude","2");

Simulate the model using the configuration stored in the Simulink.SimulationInput object simIn.

out = sim(simIn);

The model simulates for 20 seconds, using the ode45 solver and an amplitude of 2 for the Sine Wave block.

A Dashboard Scope block displays the input and output of the Integrator block.

When you use an array of Simulink.SimulationInput objects to configure a set of simulations, you can use a single call to the sim function to run the set of simulations using fast restart. Fast restart saves time in simulation by keeping the model compiled between simulation runs.

Open the model IntegrateSine. The model uses an Integrator block to integrate the output of a Sine Wave block. The output from the Integrator block is connected to an Outport block.

mdl = "IntegrateSine";
open_system(mdl)

The model IntegrateSine.

Suppose you want to run a set of six simulations that each use a different frequency value for the Sine Wave block. Create a vector that contains the frequency values for the simulations.

freqs = [0.5 1 1.5 2 2.5 3];

When you want to tune a block parameter, you can define the value of the parameter using a variable. Then, to tune the block parameter, you change the value of the variable.

Define the variable freq to use for the value of the Frequency parameter for the Sine Wave block. For the initial variable value, use the current parameter value.

blk = mdl + "/Sine Wave";
freq = str2double(get_param(blk,"Frequency"));

Set the Frequency parameter value for the Sine Wave block to freq.

set_param(blk,"Frequency","freq")

In a for loop, create an array of six Simulink.SimulationInput objects and use the setVariable function to configure each object to use a value from the vector of frequencies.

for k = length(freqs):-1:1
    simIn(k) = Simulink.SimulationInput(mdl);
    simIn(k) = setVariable(simIn(k),"freq",freqs(k));
end

Run the simulations defined by the array of SimulationInput objects simIn using the sim function. Enable fast restart using the UseFastRestart name-value argument. The UseFastRestart name-value argument is supported only when the first input argument is a Simulink.SimulationInput object. To use fast restart when the first argument is the name of a model, use the FastRestart name-value argument.

out = sim(simIn,"UseFastRestart","on");
[28-Feb-2023 11:45:06] Running simulations...
[28-Feb-2023 11:45:11] Completed 1 of 6 simulation runs
[28-Feb-2023 11:45:12] Completed 2 of 6 simulation runs
[28-Feb-2023 11:45:12] Completed 3 of 6 simulation runs
[28-Feb-2023 11:45:12] Completed 4 of 6 simulation runs
[28-Feb-2023 11:45:12] Completed 5 of 6 simulation runs
[28-Feb-2023 11:45:12] Completed 6 of 6 simulation runs

To run the same set of simulations without showing the progress messages, specify the ShowProgress name-value argument as off.

out = sim(simIn,"UseFastRestart","on","ShowProgress","off");

To monitor the progress of the simulations using the Simulation Manager, specify the ShowSimulationManager name-value argument as on. For more information about the Simulation Manager, see Simulation Manager.

out = sim(simIn,"UseFastRestart","on",...
    "ShowProgress","off","ShowSimulationManager","on");

The simulation output out is an array of Simulink.SimulationOutput objects that contain the metadata and results for each simulation. The order of SimulationOutput objects in the output array matches the order of SimulationInput objects in the input array. For example, the SimulationOutput object at index 1 contains the results of the simulation configured using the SimulationInput object at index 1.

Access the logged output signal for the results of the first simulation, which used a frequency value of 0.5.

youtPt5 = out(1).yout
youtPt5 = 
Simulink.SimulationData.Dataset 'yout' with 1 element

                         Name    BlockPath             
                         ______  _____________________ 
    1  [1x1 Signal]      output  IntegrateSine/Outport

  - Use braces { } to access, modify, or add elements using index.

Open the model IntegrateSine. The model uses an Integrator block to integrate the output of a Sine Wave block. The output from the Integrator block is connected to an Outport block.

mdl = "IntegrateSine";
open_system(mdl);

The model IntegrateSine.

Simulate the model using the current configuration parameter values.

out = sim(mdl);

The simulation runs for 10 seconds, integrating a sine wave with an amplitude of 1.

A Dashboard Scope block displays the input and output of the Integrator block.

You can modify model configuration parameter values and block parameter values in the model using the set_param function.

Configure the model to use the ode45 solver and a stop time of 20 seconds.

set_param(mdl,"Solver","ode45","StopTime","20")

Set the Amplitude parameter of the Sine Wave block to 2.

blk = strcat(mdl,"/Sine Wave");
set_param(blk,"Amplitude","2")

When you modify a configuration parameter value or block parameter value using the set_param function, the change applies to the block diagram and dirties the model file. When you call the sim function again, the simulation uses the new parameter values, which are part of the current model configuration, even if you do not save the model.

out2 = sim(mdl);

The simulation runs for 20 seconds, integrating a sine wave with an amplitude of 2.

A Dashboard Scope block displays the input and output of the Integrator block.

You can configure a simulation of a model to use different values for model configuration parameter values by specifying the configuration parameters for the simulation as name-value arguments for the sim function. The parameter values you specified are applied for the simulation and reverted when the simulation completes.

You can specify only model configuration parameter values and not block parameter values as name-value arguments for the sim function. To specify model configuration parameter values, block parameter values, and variable values for a simulation in a single input, use a Simulink.SimulationInput object instead.

Open the model IntegrateSine. The model uses an Integrator block to integrate the output of a Sine Wave block. The output from the Integrator block is connected to an Outport block.

mdl = "IntegrateSine";
open_system(mdl);

The model IntegrateSine.

Suppose you want to simulate the model using the solver ode45 and a stop time of 20 seconds. Specify the Solver and StopTime values for the simulation as name-value arguments for the sim function.

out = sim(mdl,"Solver","ode45","StopTime","20");

The model simulates through a simulation time of 20 seconds using the solver ode45.

A Dashboard Scope block displays the input and output of the Integrator block.

You can use a structure of model configuration parameter names and values to configure a simulation of a model. The configuration parameter values in the structure are applied to the model for the simulation. After simulation, any model settings that changed are reverted to the original value.

The structure input can specify only model configuration parameter values and cannot specify different block parameter or variable values to use in the simulation. To specify model configuration parameter values, block parameter values, and variable values for a simulation in a single input, use a Simulink.SimulationInput object instead.

Open the model IntegrateSine. The model uses an Integrator block to integrate the output of a Sine Wave block. The output from the Integrator block is connected to an Outport block.

mdl = "IntegrateSine";
open_system(mdl)

The model IntegrateSine.

Create the structure SimConfig that configures a simulation to use the ode45 solver and a stop time of 20 seconds. The structure contains a field for each configuration parameter to modify in the simulation. The name of each field matches the programmatic name for each parameter. The value of each field specifies the value to use for that parameter in the simulation.

simConfig.Solver = "ode45";
simConfig.StopTime = "20";

Simulate the model using the model configuration parameter values from the structure.

out = sim(mdl,simConfig);

The model simulates through a simulation time of 20 seconds using the ode45 solver.

A Dashboard Scope block displays the input and output of the Integrator block.

A Simulink.ConfigSet object stores a set of model configuration parameter values. You can specify a Simulink.ConfigSet object as an input to the sim function. The configuration set from the object is applied to the model for the simulation. After simulation, the original configuration set is restored in the model.

A Simulink.Configset object stores only model configuration parameter values. To specify model configuration parameter values, block parameter values, and variable values for a simulation in a single input, use a Simulink.SimulationInput object instead.

Open the model IntegrateSine. The model uses an Integrator block to integrate the output of a Sine Wave block. The output from the Integrator block is connected to an Outport block.

mdl = "IntegrateSine";
open_system(mdl)

The model IntegrateSine.

Use the getActiveConfigSet function to get a Simulink.ConfigSet object for the current model configuration.

mdlConfig = getActiveConfigSet(mdl);

Use the copy function to create a copy of the Simulink.ConfigSet object to modify.

simConfig = copy(mdlConfig);

Modify the Simulink.ConfigSet object simConfig to use the solver ode45 and a stop time of 20 seconds.

set_param(simConfig,"Solver","ode45","StopTime","20");

Simulate the model using the configuration parameters in the Simulink.Configset object simConfig.

out = sim(mdl,simConfig);

The model simulates through a simulation time of 20 seconds using the ode45 solver.

A Dashboard Scope block displays the input and output of the Integrator block.

Input Arguments

collapse all

Simulation inputs and configuration, specified as a Simulink.SimulationInput object or an array of Simulink.SimulationInput objects. The properties of the SimulationInput object specify options and parameter values to use in the simulation, including:

  • The model to simulate

  • Source variables or files for external input data

  • Block parameter values to use for the simulation

  • Model configuration parameter values to use for the simulation

The values defined in the properties of the SimulationInput object are applied to the model for the simulation and reverted at the end of simulation.

Model to simulate, specified as a string or a character vector that defines the name of the model or as a model handle (since R2024a).

Example: simOut = sim("vdp") simulates the model named vdp using the parameter values currently configured in the model.

Data Types: char | string

Model configuration to simulate, specified as a structure. The fields of the structure are the names of model configuration parameters. The value for each field indicates the parameter value to use in simulation. For example, to simulate a model from a start time of 5 to a stop time of 10, create this structure:

paramStruct.StartTime = "5";
paramStruct.StopTime = "10";

Data Types: struct

Model configuration to simulate, specified as a Simulink.ConfigSet object.

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: simout = sim(simin,UseFastRestart="on") runs a set of simulations configured using an array of Simulink.SimulationInput objects with fast restart enabled.

Example: simout = sim(mdl,Solver="ode15s",StopTime="30") configures a simulation of the model mdl to use the solver ode15s with a stop time of 30 seconds.

The sim function supports different name-value arguments depending on whether you specify the first input as one or more Simulink.SimulationInput objects or as the name or handle of the model to simulate. In addition to the arguments listed on this page, you can specify values for model configuration parameters using inputs to the sim function.

  • When the first input argument is one or more Simulink.SimulationInput objects, configure model parameter values for the simulation on the input object using the setModelParameter function.

  • When the first input argument is the model name or handle, specify any model configuration parameter as a name-value argument.

Simulink.SimulationInput Object Syntax

collapse all

Option to enable fast restart, specified as "off" or "on". Fast restart reduces the time required to run a set of simulations by skipping the compilation and termination phases when appropriate. For more information, see How Fast Restart Improves Iterative Simulations.

Consider using fast restart when you use a single call to the sim function to run multiple simulations of the same model by specifying an array of SimulationInput objects.

This argument has no effect when you specify a scalar SimulationInput object.

This argument is supported only when you specify the first input argument for the sim function as one or more Simulink.SimulationInput objects.

Example: sim(simIn,UseFastRestart="on")

Data Types: char | string

Option to skip subsequent simulations if simulation error occurs, specified as "off" or "on". This argument has an effect only when you use a single call to the sim function to run multiple simulations by specifying an array of Simulink.SimulationInput objects as the first argument.

  • "off" — If a simulation error occurs, the software captures the error in the simulation output and continues to run any subsequent simulations.

    For example, if you specify a vector that contains five SimulationInput objects and an error occurs during the second simulation, the software captures the error in the output for the second simulation and continues to run the third, fourth, and fifth simulations.

  • "on" — If a simulation error occurs, the software captures the error in the simulation output and does not run any subsequent simulations.

    For example, if you specify a vector that contains five SimulationInput objects and an error occurs during the second simulation, the software captures the error in the output for the second simulation and does not run the third, fourth, and fifth simulations. The sim function returns an empty Simulink.SimulationOutput object for each simulation that does not run.

This argument has no effect when you run a single simulation by specifying a scalar SimulationInput object. (since R2024a)

This argument is supported only when you specify the first input argument for the sim function as one or more Simulink.SimulationInput objects.

Example: sim(simIn,StopOnError="on")

Tips

  • When you run multiple simulations by specifying an array of SimulationInput objects, the software always enables the CaptureErrors parameter for each simulation. For individual simulations you run using the sim function, CaptureErrors is off by default.

  • To control whether the software captures errors in the simulation output for single simulations you run by specifying a scalar SimulationInput object, specify the CaptureErrors parameter for the simulation using the setModelParameter function. (since R2024a)

  • When you run multiple simulations using a single call to the sim function or when you configure an individual simulation to capture simulation errors in the simulation output, you can view information about the error and the simulation in the simulation output.

    • To view the message, use the ErrorMessage property of the SimulationOutput object.

    • For more information about the error, use the ExecutionInfo property of the Simulink.SimulationMetadata object. The ErrorDiagnostic field includes information about the error, including the simulation phase in which the error occurred.

Data Types: char | string

Option to indicate simulation progress, specified as "off" or "on".

  • "off" — Simulations run without displaying progress messages.

  • "on" — Progress updates are displayed as simulations progress.

The default value for this parameter depends on the size of the first input argument:

  • When the first input argument is a scalar Simulink.SimulationInput object, the default value is "off".

  • When the first input argument is an array of Simulink.SimulationInput objects, the default value is "on".

This argument is supported only when you specify the first input argument for the sim function as one or more Simulink.SimulationInput objects.

Example: sim(simIn,ShowProgress="on")

Option to open Simulation Manager, specified as "off" or "on". Use the Simulation Manager to monitor the progress of simulations you run. Consider using the Simulation Manager when you run multiple simulations by specifying an array of Simulink.SimulationInput objects.

This argument is supported only when you specify the first input argument for the sim function as one or more Simulink.SimulationInput objects.

Example: sim(simIn,ShowSimulationManager="on")

Model Syntax

collapse all

Option to enable fast restart, specified as "on" or "off".

  • "on" — Enables fast restart for simulation. Fast restart saves time in iterative simulation workflows by skipping compilation and termination after compiling the model for the first simulation you run after enabling fast restart.

    When you enable fast restart using this name-value argument, if the model is not already initialized in fast restart, the software compiles the model before running the simulation. At the end of the simulation, the model remains initialized in fast restart.

  • "off" — Disables fast restart for simulation. With fast restart disabled, each time you run a simulation, the software compiles the model, initializes the simulation, runs the simulation, and then terminates the simulation.

By default, fast restart is disabled, and simulations you run using the sim function do not enable fast restart. For more information, see How Fast Restart Improves Iterative Simulations.

This argument is supported only when you specify the first input argument for the sim function as a model name or handle.

Example: sim("myModel",FastRestart="on")

Tips

  • When you specify a scalar SimulationInput object as the first input to the sim function, specify this parameter on the SimulationInput object using the setModelParameter function. (since R2024a)

  • When you specify an array of SimulationInput objects as the first input to the sim function, enable fast restart for the batch of simulations by specifying the UseFastRestart name-value argument.

  • If you specify this name-value argument as "off" when you simulate a model that is initialized in fast restart, the software terminates the previous simulation and compiles the model before running the current simulation.

  • If you enable fast restart using the Simulink Editor or the set_param function, simulations you run using the sim function use fast restart even if you do not specify the FastRestart name-value argument.

Data Types: char | string

Option to capture errors and return simulation output if simulation error occurs, specified as "off" or "on".

BehaviorCaptureErrors="off" (default)CaptureErrors="on"
Issuing exceptions for simulation errors

The software issues exceptions for simulation errors.

The exception stops both the simulation in which the error occurred and the process that invoked the simulation.

The software does not issue exceptions for simulation errors.

The simulation error stops the simulation. However, if another function or a script invoked the simulation, the function or script execution continues.

Error reporting

Errors that occur during simulation are reported in the MATLAB® Command Window.

Information about the simulation errors, including the message and the simulation phase in which the error occurred, is captured in the simulation output.

Simulation results

Issuing an exception stops the simulation immediately. The sim function does not return simulation results.

The sim function returns simulation results and metadata up to the simulation time at which the error occurred.

This argument is supported only when you specify the first input argument for the sim function as a model name or handle.

Example: sim("myModel",CaptureErrors="on")

Tips

  • This option is not supported for software-in-the-loop (SIL) and processor-in-the-loop (PIL) simulations.

  • When you specify a scalar SimulationInput object as input to the sim function, specify this parameter on the SimulationInput object using the setModelParameter function. (since R2024a)

  • When you configure an individual simulation to capture simulation errors and when you run multiple simulations by specifying an array of SimulationInput objects, you can view information about the error and the simulation in the simulation results.

    • To view the message, use the ErrorMessage property of the SimulationOutput object.

    • For more information about the error, use the ExecutionInfo property of the Simulink.SimulationMetadata object. The ErrorDiagnostic field includes information about the error, including the simulation phase in which the error occurred.

Data Types: char | string

Option to start programmatic simulation debugging session, specified as "off" or "on".

This argument is supported only when you specify the first input argument for the sim function as a model name or handle.

Example: sim("modelName",Debug="on")

Data Types: char | string

Option to disable rebuilding rapid accelerator target, specified as "on" or "off". When you specify this argument as "on", changes that require rebuilding the rapid accelerator target are ignored. When you use this option, modify only options that do not require rebuilding the rapid accelerator target.

This argument is supported only when you specify the first input argument for the sim function as a model name or handle.

Example: sim("modelName",RapidAcceleratorUpToDateCheck="off")

Tips

To specify this option for a simulation configured using a Simulink.SimulationInput object, use the setModelParameter function.

simIn = Simulink.SimulationInput("MyModel");
simIn = setModelParameter(simIn,RapidAcceleratorUpToDateCheck="off");

Data Types: char | string

Maximum simulation run time, specified as a positive scalar. Specify the time, in seconds, to allow the simulation to run. If the simulation runs for longer than the value you specify, the software issues a warning and stops the simulation. For example, if you specify TimeOut as 30, the software stops the simulation and issues a warning if computing simulation results takes more than 30 seconds.

The TimeOut parameter specifies a limit on the amount of clock time for a simulation to run. To specify the maximum time value to simulate, use the Stop time parameter.

This argument is supported only when you specify the first input argument for the sim function as a model name or handle.

Example: sim("MyModel",TimeOut=60) configures a simulation to run for a maximum run time of 60 seconds.

Tips

  • Consider specifying a timeout when you run multiple variable-step simulations in serial. If simulation conditions constrain the step size so that the solver starts taking many very small time steps, the simulation can time out so that subsequent simulations can run.

  • To specify this option for a simulation configured using a Simulink.SimulationInput object, use the setModelParameter function.

    simIn = Simulink.SimulationInput("MyModel");
    simIn = setModelParameter(simIn,TimeOut=60);

Option to display summary of parameters before simulation, specified as "siminfo".

This argument is supported only when you specify the first input argument for the sim function as a model name or handle.

Example: sim("modelName",Trace="siminfo")

Data Types: char | string

Output Arguments

collapse all

Simulation results and metadata, returned as a Simulink.SimulationOutput object, an array of Simulink.SimulationOutput objects, or a vector. The Simulink.SimulationOutput object contains all data logged from simulation as well as metadata about the simulation, including timing information and diagnostics.

When you specify the model name or handle as the only input argument and the model you simulate has the Single simulation output parameter disabled, the output from the sim function is a vector of the major time hits that occurred in the simulation. To ensure that the sim function returns results in a consistent format for any syntax, save the model with the Single simulation output parameter enabled.

Tips

  • To ensure the sim function returns results in the same format for every syntax, save your model with the Single simulation output parameter enabled. With this option enabled, simulation results are returned as one or more Simulink.SimulationOutput objects that each contain all logged data simulation metadata, including timing information and diagnostics, for a simulation. Returning all simulation data and metadata in a single object facilitates analyzing results from multiple simulations.

  • To get a list of model configuration parameters, use the getActiveConfigSet function and the get_param function. For example, to see the configuration parameters for the model vdp, enter these commands in the MATLAB Command Window.

    configSet = getActiveConfigSet("vdp");
    configSetNames = get_param(configSet,"ObjectParameters")

    The get_param function returns a list of all the model configuration parameters, such as StopTime, SaveTime, SaveState, SaveOutput, and SignalLogging.

  • When you simulate a model hierarchy, model configuration parameters you specify as input arguments to the sim function apply to the top model.

  • When you run a simulation using the sim function, the simulation runs until an error occurs or the simulation reaches the specified stop time. To run or script a programmatic simulation in which you can control the simulation execution and tune parameter values during simulation, use the Simulation object. (since R2024a) For more information, see Run Simulations Programmatically.

  • You can interact with simulations using both the MATLAB Command Window and the Simulink Editor by issuing simulation commands using the set_param function. For more information, see Run Simulations Programmatically.

  • When you simulate a model with infinite stop time, stop the simulation from the MATLAB Command Window by pressing Ctrl+C. The simulation stops, and simulation results are not saved in the MATLAB workspace.

  • Configure logging for time, states, and outputs using the Configuration Parameters dialog box. On the Modeling tab, under Setup, click Model Settings. Then, in the Configuration Parameters dialog box, select Data Import/Export.

  • To log signals throughout a model, use signal logging or logging blocks such as the To Workspace block or the Record block. For more information about signal logging, see Save Signal Data Using Signal Logging.

Version History

Introduced before R2006a

expand all