Main Content

Run Simulations Programmatically

To run simulations programmatically, you can write scripts or issue commands in the MATLAB® Command Window. Several interfaces provide programmatic simulation capabilities. Each interface has different capabilities for configuring simulation behavior and interacting with the simulation as it runs.

Programmatic InterfaceGeneral Use Case
sim function

Configure and run simulations.

Simulation object

Configure and run simulations, tune variable and parameter values during simulation, and write scripts that control simulation execution.

set_param function with SimulationCommand name-value argument

Interact with simulation using both the MATLAB Command Window and the Simulink Editor.

Simulations you run programmatically using the sim function, the Simulation object, or the set_param function run one at a time, in serial. To run parallel or batch simulations, use the parsim function or the batchsim function.

Decide How to Run or Script Programmatic Simulations

In general, the sim function supports most requirements for running and scripting individual and serial programmatic simulations where you do not intend to interact with the model during the simulation.

When you want to interact with a simulation programmatically during the simulation, use a Simulation object. Using a Simulation object, you can control the simulation execution and tune parameter and variable values during simulation. You can write MATLAB scripts that modify parameter or variable values based on results and values computed in the simulation.

While you can programmatically interact with simulations you run using Simulation objects, you cannot interact with the model or simulation associated with a Simulation object using the Simulink Editor while the simulation has a status other than inactive. Issuing simulation commands using the set_param function allows you to interact with a model both programmatically from the MATLAB command prompt and interactively using the Simulink Editor. Simulation commands are supported in simulations you start by clicking Run in the Simulink Editor or by issuing the start simulation command.

The table summarizes the functionality available for scripting programmatic simulations that use the sim function and for those that use the Simulation object.

Action or Optionsim FunctionSimulation object
Configure simulation without directly modifying the model

You can specify parameter and variable values to override the values saved in the model using a Simulink.SimulationInput object, a structure, a Simulink.ConfigSet object, or name-value arguments.

The override values that you specify are applied for the simulation and revert once the simulation completes.

You can specify parameter and variable values to override the values saved in the model by creating the Simulation object from an existing Simulink.SimulationInput object or by specifying the override values on the Simulation object.

The override values that you specify are applied for the simulation and revert once the simulation completes.

Tune parameter and variable values during simulationNot supported.

Use the setVariable, setModelParameter, and setBlockParameter functions to tune parameter values during simulation.

Stop simulation

In the MATLAB Command Window, press Ctrl+C.

Call the stop function or the terminate function.
Pause simulation

Not supported.

Call the pause function.

Use the step function to specify the amount to advance the simulation before pausing.

Issue command in MATLAB Command Window

Not supported.

The MATLAB command prompt is not available during simulation.

Supported.

The MATLAB command prompt is available while the simulation is running, except when you advance the simulation by calling the step function.

View simulation results using visualization blocks, such as the Scope block

Supported for normal and accelerator mode simulations.

Not supported for rapid accelerator simulations.

Not supported.
Port value labelsNot supported.Not supported.
Step through simulation

Not supported.

To advance the simulation, use the step function.

Stepping backward is not supported.

Signal breakpoints

Not supported.

Not supported.
Pause at or after specified time

Not supported.

Use the step function with the PauseTime name-value argument.
Capture information about simulation errors in simulation output instead of issuing exception

Specify the CaptureErrors name-value argument as "on".

Specify the CaptureErrors parameter as "on" using the setModelParameter.

Fast restartSupported.Supported.
Simulation pacingSupported.Supported.
Simulation timeout

Specify a maximum amount of time to allow the sim function to run using the Timeout name-value argument.

Not supported.
Query simulation status

Not supported.

Simulation execution blocks the MATLAB thread.

The Status property of the Simulation object indicates the current simulation status.
Run simulation in MATLAB session started using the -nodesktop or -nodisplay options for matlab (macOS) or matlab (Linux).Supported.Supported.

Run and Script Simulations Using sim Function

The sim function has several syntaxes you can use to run and configure simulations programmatically. When you want to simulate the model using the current values for all model configuration parameter values, block parameter values, variable values, and so on, use the most basic syntax, specifying only the name of the model as an input argument.

out = sim("ModelName");

This syntax returns a single Simulink.SimulationOutput object that contains all simulation results, except when the Single simulation output parameter is disabled. To ensure you can write consistent code for all simulations you run programmatically, enable the Single simulation output parameter.

When you want to configure the simulation, for example, by specifying values for model configuration parameter values, block parameter values, and variables values, use a Simulink.SimulationInput object to specify the simulation configuration. This command shows the basic syntax for using a SimulationInput object. The SimulationInput object, stored in a variable named simin, is the only input argument. The simulation results are always returned as a single Simulink.SimulationOutput object.

out = sim(simin);

The table summarizes the options you can configure and use cases for using each syntax.

sim SyntaxSimulation Configuration Options
out = sim("ModelName");

Simulate model using current values for configuration parameter, block parameter, and variable values.

out = sim(simin);

Specify simulation configuration using Simulink.SimulationInput object with override values for:

  • Model configuration parameters

  • Variables

  • External inputs

  • Initial state

  • Block parameters

Use name-value arguments to configure additional options, such as whether to:

  • Run simulations using fast restart.

  • Capture errors in the simulation output or issue MATLAB exceptions.

  • Open the Simulation Manager.

out = sim("ModelName",Name=Value);

Use name-value arguments to configure simulation options, such as:

  • Model configuration parameters

  • Simulation pacing options

  • Whether to simulate using fast restart

  • Whether to capture errors in the simulation output or issue MATLAB exceptions

out = sim("ModelName",paramstruct);

Specify model configuration parameter values and simulation options using a structure with field names that match each parameter name and field values that specify the value to use for each parameter.

For example, to specify the StopTime parameter value as 20, create a structure with a field named StopTime that has a value of "20".

paramStruct.StopTime = "20";
out = sim("ModelName",configset);

Specify model configuration parameter values using a Simulink.ConfigSet object.

Run and Script Simulations Using Simulation Objects

A Simulation object represents a simulation of a model and provides an interface to control and interact with the simulation as it runs. The MATLAB command prompt is available while the simulation is running, unlike simulations you run using the sim function. Using the Simulation object, you can:

  • Write scripts that control and interact with simulations using logic in MATLAB code based on simulation results you can access during run time.

  • Step forward through major time steps in simulation.

  • Tune parameter and variable values during simulation.

  • Build apps using App Designer to control, interact with, and monitor simulations.

  • Deploy simulation scripts and apps using Simulink® Compiler™.

The table summarizes the Simulation object functions you can use to control the simulation execution.

FunctionDescriptionDetails
initialize

Initialize simulation.

The MATLAB command prompt is unavailable until initialization is complete.

start

Start simulation.

If you start a simulation that is not initialized, the start function initializes the simulation before starting it. The MATLAB command prompt is unavailable until initialization is complete, at which point the simulation starts and the MATLAB command prompt becomes available.

step

Advance simulation by a specified amount and then pause.

You can advance the simulation by a single major time step, by a specified number of major time steps, and to or past a specified simulation time. The simulation pauses after advancing by the specified amount.

The MATLAB command prompt is unavailable while the simulation advances.

pausePause active simulation.

The pause function sends an immediate request to pause the simulation. The simulation pauses after completing processes that must finish without interruption.

The MATLAB command prompt is unavailable while the simulation pauses.

resumeContinue paused simulation.

The MATLAB command prompt is unavailable while resuming the simulation and becomes available once the simulation starts to execute.

stopStop active simulation before simulation stop time.

The stop function sends an immediate request to stop the simulation. The simulation stops after completing processes that must finish without interruption.

When a simulation reaches the simulation stop time, the simulation stops on its own, except when you advance a normal or accelerator mode simulation through the last time step using the step function. In this case, the simulation pauses after the last time step.

terminateTerminate simulation.

Simulations that do not have fast restart enabled terminate when they stop. Fast restart simulations remain compiled after stopping so that you do not need to initialize subsequent simulations. Simulations that run after you termination require initialization.

You can configure simulations by specifying the initial state, external inputs, model parameter, block parameter, and variable values to use in the simulation. The values you specify override the values saved in the model during simulation and revert when the simulation completes. You can also modify the values of tunable parameter and variable values during simulation. The table summarizes the Simulation object functions available for configuring the simulation.

FunctionDescriptionDetails
setInitialStateSpecify initial state or operating point for simulation.The initial state is tunable only between simulations and not during simulation.
setExternalInputSpecify external input data to load using top-level input ports.External input data is tunable only between simulations and not during simulation.
setModelParameterSpecify values for model configuration parameters to use in simulation.Most configuration parameters are tunable only between simulations and not during simulation.
setVariableSpecify variable values to use in simulation.You can configure the initial variable values to use in the simulation and tune variable values during simulation.
setBlockParameterSpecify block parameter values to use in simulation.

Some block parameters are tunable only between simulations and not during simulations.

Deployed simulations do not support tuning block parameter values. To tune block parameter values in a deployed simulation, specify the block parameter value as a variable and then tune the variable value instead.

Interact with Simulations by Issuing Simulation Commands

Starting a simulation by using the set_param function to issue a simulation command is equivalent to starting a simulation from a user interface, such as by clicking Run in the Simulink Editor. The simulation commands programmatically initiate the same actions you can initiate using a user interface, such as the Simulink Editor. Use simulation commands as a convenience in workflows that involve switching between the MATLAB Command Window and the Simulink Editor or another user interface.

To issue a simulation command, specify the SimulationCommand name-value argument for the set_param function. For example, this command issues the start simulation command for a model named MyModel.

set_param("MyModel",SimulationCommand="start")

Because issuing the start simulation command performs the same action as starting a simulation from a user interface, you can issue simulation commands to control and interact with simulations that you start from a user interface or by issuing the start simulation command. Simulations that you start by issuing the start simulation command offer the same functionality and support as simulations you start from a user interface, including:

  • Tuning parameter values during simulation using a user interface or using the set_param function

  • Viewing signal values and simulation results in the block diagram using port value labels and visualization blocks, such as the Scope block

  • Controlling simulation execution by pausing and stepping backward and forward using the Pause, Step Forward, and Step Back buttons

  • Debugging tools, such as signal breakpoints

Errors that occur as a result of issuing a simulation command or during simulations that you start by issuing the start simulation command are reported to the Diagnostic Viewer, except for errors that occur while executing the update simulation command.

When you issue simulation commands during simulation, the software does not execute the command immediately. The software issues the command only after currently running processes that cannot be interrupted have finished. For example, if you issue a simulation command while the solver is determining the next time step, the software executes the simulation command only after the solver finishes propagating time.

Not all actions available in the Simulink Editor have a corresponding simulation command. The table describes each simulation command and the corresponding user interface actions and keyboard shortcuts.

Simulation Command DescriptionEquivalent User Interface ActionKeyboard Shortcut
set_param(mdl,SimulationCommand="start")

Start simulation.

Click Run.

Ctrl+T or F5

set_param(mdl,SimulationCommand="stop")

Stop simulation.

Click Stop.

Ctrl+Shift+T

set_param(mdl,SimulationCommand="pause")

Pause simulation.

Click Pause.

Ctrl+T or F5

set_param(mdl,SimulationCommand="continue")

Resume paused simulation.

Click Continue.

Ctrl+T or F5

set_param(mdl,SimulationCommand="update")

Update diagram.

In the Simulink Toolstrip, in the Prepare section, click Update Model.Ctrl+D
set_param(mdl,SimulationCommand="writedatalogs")

Write data logging variables to the workspace.

Not supported.Not supported.

When you start a simulation from a user interface or by issuing a simulation command, you can query the simulation status using the get_param function. For example, this command queries the simulation status for a model named MyModel.

simstatus = get_param("MyModel","SimulationStatus")

This table describes the simulation status that corresponds to each return value for the SimulationStatus argument.

SimulationStatus ValueDescription
stoppedSimulation stopped.
initializingExecuting initialization phase.
runningRunning execution phase.
pausedPaused in execution phase.
compiledModel compiled.
updatingUpdating diagram.
terminatingExecuting termination phase.
externalSimulating with Simulink Coder™.

See Also

Functions

Objects

Related Topics