Main Content

Run Simulations Programmatically

To programmatically run a simulation, you can write scripts or issue commands in the MATLAB® Command Window:

  • Using the sim function

  • Using the set_param function to issue simulation commands using the SimulationCommand name-value argument.

Each of these options provides different capabilities for configuring the simulation behavior and interacting with the simulation as it runs.

Simulations you run programmatically using the sim function 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.

Decide How to Run 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 model programmatically during the simulation, you can use the set_param function to issue simulation commands. Simulation commands are supported in simulations you start by clicking Run or by issuing the start simulation command using the set_param function. Issuing simulation commands can be convenient in workflows that involve switching between the MATLAB Command Window and the Simulink® Editor.

Fast restart is supported for programmatic simulations you run by issuing simulation commands and by using the sim function. No matter how you enable fast restart,the model remains initialized in fast restart at the end of the simulation, and you can run the next simulation by clicking Run, by issuing a simulation command, or by calling the sim function.

The table summarizes differences between simulations run using the sim function and those run using the set_param function.

Action or Optionsim Functionset_param Simulation Commands
Configure model for simulation

Specify values for model configuration parameters, block parameters, and variables to use in simulation using input arguments for the sim function.

The values you specify are applied during simulation and reverted after the simulation completes. Configuring simulations using input arguments for the sim function does not dirty the model.

Specify values for model configuration parameters and block parameters programmatically using the set_param function.

You can also configure the simulation using tools such as the Property Inspector, the Configuration Parameters dialog box, and the Block Parameters dialog box.

Configuring the model for this type of simulation dirties the model.

Start simulation

Call the sim function.

set_param(mdl,"SimulationCommand","Start")

In the Simulink Toolstrip, click Run.

Stop simulation

In the MATLAB Command Window, press Ctrl+C.

set_param(mdl,"SimulationCommand","Stop")

In the Simulink Toolstrip, click Stop.

Pause simulation

Not supported.

set_param(mdl,"SimulationCommand","Pause")

In the Simulink Toolstrip, click Pause.

Resume simulation

Not applicable because pausing simulation is not supported.

set_param(mdl,"SimulationCommand","Continue")

In the Simulink Toolstrip, click Continue.

Issue command in MATLAB Command Window

Not supported.

sim function execution blocks the MATLAB thread.

Supported.

Visualization blocks such as Scope blocks

Visualizations update during only normal and accelerator mode simulations.

Visualizations update during normal, accelerator, and rapid accelerator simulations.

Port value labels

Not supported.

Port value labels display signal values in the block diagram during normal, accelerator, and rapid accelerator mode simulations.

Step forward and backward in simulation

Not supported.

Supported for normal and accelerator mode simulations.

In the Simulink Toolstrip, on the Simulation tab, click Step Forward or Step Back.

Signal breakpoints

Not supported.

Supported for normal mode in simulations to pause within a time step.

Supported for normal and accelerator mode in simulations configured to pause only between time steps.

Pause at or after specified time

Not supported.

Supported for normal and accelerator mode simulations.
Fast restart

To run simulations using fast restart:

  • Specify the UseFastRestart name-value argument as "on" when you specify the first input argument as one or more SimulationInput objects.

    out = sim(simIn,"UseFastRestart","on");
  • Specify the FastRestart name-value argument as "on" when you specify the first input argument as a string or a character vector that defines the name of the model. After simulation, the model stays initialized in fast restart.

    out = sim("MyModel","FastRestart","on");

Use the set_param function to enable fast restart.

set_param(mdl,"FastRestart","on")

In the Simulink Toolstrip, on the Simulation tab, in the Simulate section, click Fast Restart.

Simulation pacing

Configure simulation pacing by specifying values for the simulation pacing parameters for the model.

  • EnablePacing — Enable or disable simulation pacing.

  • PacingRate — Specify the approximate pacing rate as a ratio of simulation time to wall clock time.

Configure simulation pacing options by using the Simulation Pacing Options dialog box or by specifying values for the simulation pacing parameters programmatically.

  • EnablePacing — Enable or disable simulation pacing .

  • PacingRate — Specify the approximate pacing rate as a ratio of simulation time to wall clock time.

Simulation timeout

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

Not supported.

Stop the simulation at any time by issuing a simulation command or by clicking Stop.

Error handling

Specify whether to capture errors in the simulation output or issue errors as MATLAB exceptions:

  • Use the StopOnError name-value argument when you specify the first input argument as one or more SimulationInput objects.

  • Use the CaptureErrors name-value argument when you specify the first input argument as a string or a character vector that defines the name of the model.

Errors are reported to the Diagnostic Viewer.

Query simulation status

Not supported.

sim function execution blocks the MATLAB thread.

get_param(mdl,"SimulationStatus")
Run simulation in MATLAB session started using the -nodesktop or -nodisplay options for matlab (macOS) or matlab (Linux).Supported.Not supported.

Run Simulations Using the 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.

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.

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 Control Simulations by Issuing Simulation Commands

When you start a simulation from a user interface, such as the Simulink Editor, or by using the set_param function to issue a simulation command, you can:

  • Control and interact with the simulation by using the set_param function to issue simulation commands.

  • Use the get_param function to query the simulation status.

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.

This table describes the simulation status that corresponds to each return value for the SimulationStatus name-value 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