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 Interface | General 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 Option | sim Function | Simulation 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 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 The override values that you specify are applied for the simulation and revert once the simulation completes. |
Tune parameter and variable values during simulation | Not supported. | Use the |
Stop simulation | In the MATLAB Command Window, press Ctrl+C. | Call the stop function or the
terminate function. |
Pause simulation | Not supported. | Call the Use the
|
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 |
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 labels | Not supported. | Not supported. |
Step through simulation | Not supported. | To advance the simulation, use the 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 | Specify the |
Fast restart | Supported. | Supported. |
Simulation pacing | Supported. | Supported. |
Simulation timeout | Specify a maximum amount of time to allow the | 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 Syntax | Simulation 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
Use name-value arguments to configure additional options, such as whether to:
|
out = sim("ModelName",Name=Value); | Use name-value arguments to configure simulation options, such as:
|
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 paramStruct.StopTime = "20"; |
out = sim("ModelName",configset); | Specify model configuration parameter values using a |
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.
Function | Description | Details |
---|---|---|
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
|
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. |
pause | Pause active simulation. | The The MATLAB command prompt is unavailable while the simulation pauses. |
resume | Continue paused simulation. | The MATLAB command prompt is unavailable while resuming the simulation and becomes available once the simulation starts to execute. |
stop | Stop active simulation before simulation stop time. | The 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
|
terminate | Terminate 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.
Function | Description | Details |
---|---|---|
setInitialState | Specify initial state or operating point for simulation. | The initial state is tunable only between simulations and not during simulation. |
setExternalInput | Specify external input data to load using top-level input ports. | External input data is tunable only between simulations and not during simulation. |
setModelParameter | Specify values for model configuration parameters to use in simulation. | Most configuration parameters are tunable only between simulations and not during simulation. |
setVariable | Specify variable values to use in simulation. | You can configure the initial variable values to use in the simulation and tune variable values during simulation. |
setBlockParameter | Specify 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
functionViewing 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 | Description | Equivalent User Interface Action | Keyboard 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 Value | Description |
---|---|
stopped | Simulation stopped. |
initializing | Executing initialization phase. |
running | Running execution phase. |
paused | Paused in execution phase. |
compiled | Model compiled. |
updating | Updating diagram. |
terminating | Executing termination phase. |
external | Simulating with Simulink Coder™. |