Main Content

Run Simulations Programmatically

You can simulate a model programmatically in two ways:

  • Via sim command.

  • Via the run button

When performing simulations with the sim command, you use the command line to perform operations on your simulation. Performing simulations with the Run button implies that you can interact with the simulation using the Simulink® UI to perform any other additional operations. The following table elaborates the differences between these two approaches.

ActionsNon-Interactive Simulation (sim Command Simulations)Interactive Simulation (Run Button Simulations)
Allowed level of interactionLowHigh
Start a simulationsim command Run/set_param(mdl,'SimulationCommand','Start')
Stopping a simulationCtrl-C on the command line

set_param(mdl,'SimulationCommand','Stop')/ Stop

Pausing a simulationNoYes. set_param(mdl,'SimulationCommand','Pause') / Pause
MATLAB® prompt available while simulation runsNoYes
Scopes update while simulation runsYes, except in Rapid Accelerator ModeYes
Simulation StepperNoYes, except in Rapid Accelerator Mode
Conditional PausesNoYes, except in Rapid Accelerator Model
Port value displays available while simulation runs?NoYes
Supports simulation pacingYesYes
Supports TimeOut optionYes No
Error handlingMATLAB exception, unless CaptureErrors is onReported to the Diagnostic Viewer

sim Command Simulations

You can programmatically simulate a model with the sim function by using the specified techniques to specify parameter values. In addition to simulating a model, you can use the sim command to enable simulation timeout, capture simulation errors, and access simulation metadata when your simulation is complete.

Specify Parameter Name-Value Pairs

This example shows how to programmatically simulate a model, specifying model parameters as name-value pairs.

Simulate the vdp model with parameter values specified as consecutive name-value pairs.

simOut = sim('vdp','SimulationMode','normal',...
            'SaveState','on','StateSaveName','xout',...
            'SaveOutput','on','OutputSaveName','yout',...
            'SaveFormat', 'Dataset');
outputs = simOut.yout
outputs = 

  Simulink.SimulationData.Dataset
  Package: Simulink.SimulationData

  Characteristics:
              Name: 'yout'
    Total Elements: 2

  Elements:
    1 : 'x1'
    2 : 'x2'

  -Use get or getElement to access elements by index or name.
  -Use addElement or setElement to add or modify elements.

You simulate the model in Normal mode, specifying an absolute tolerance for solver error. The sim function returns SimOut, a single Simulink.SimulationOutput object that contains all of the simulation outputs: logged time, states, and signals.

Plot the output signal values against time.

x1 = (outputs.get('x1').Values);
x2 = (outputs.get('x2').Values);
plot(x1); hold on;
plot(x2);
title('VDP States')
xlabel('Time'); legend('x1','x2')

Plot of the vdp simulation

Enable Simulation Timeouts

If you are running multiple simulations in a loop and are using a variable-step solver, consider using sim with the timeout parameter. If, for some reason, a simulation hangs or begins to take unexpectedly small time steps, it will time out. Then, the next simulation can run.

N = 100;
simOut = repmat(Simulink.SimulationOutput, N, 1);
for i = 1:N
		simOut(i) = sim('vdp', 'timeout', 1000);
end

Capture Simulation Errors

If an error causes your simulation to stop, you can see the error in the simulation metadata. In this case, sim captures simulation data in the simulation output object up to the time it encounters the error, enabling you to do some debugging of the simulation without rerunning it. To enable this feature, use the CaptureErrors parameter with the sim function.

Another advantage of this approach is that the simulation error does not also cause sim to stop. Therefore, if you are using sim in a for loop, for example, subsequent iterations of the loop will still run.

simOut = sim('my_model', 'CaptureErrors', 'on');
simOut.getSimulationMetadata.ExecutionInfo
ans = 

  struct with fields:

               StopEvent: 'DiagnosticError'
         StopEventSource: []
    StopEventDescription: 'Division by zero in 'my_model/Divide''
         ErrorDiagnostic: [1×1 struct]
      WarningDiagnostics: [0×1 struct]

Access Simulation Metadata

This example shows you how to access simulation metadata once your simulation is complete. You can run any kind of simulation and access its metadata.

This example simulates the model with parameter values specifies as name-value pairs. Run the simulation.

simOut = sim('vdp','SimulationMode','normal','AbsTol','1e-5',...
            'SaveState','on','StateSaveName','xoutNew',...
            'SaveOutput','on','OutputSaveName','youtNew',...
 'SaveFormat', 'StructureWithTime');

Access the ModelInfo property, which has basic information about the model and solver.

simOut.getSimulationMetadata.ModelInfo
ans = 

  struct with fields:

                  ModelName: 'vdp'
               ModelVersion: '1.6'
              ModelFilePath: 'C:\MyWork'
                     UserID: 'User'
                MachineName: 'MyMachine'
                   Platform: 'PCWIN64'
    ModelStructuralChecksum: [4×1 uint32]
             SimulationMode: 'normal'
                  StartTime: 0
                   StopTime: 20
                 SolverInfo: [1×1 struct]
            SimulinkVersion: [1×1 struct]
                LoggingInfo: [1×1 struct]

Inspect the solver information.

simOut.getSimulationMetadata.ModelInfo.SolverInfo
ans = 

  struct with fields:

           Type: 'Variable-Step'
         Solver: 'ode45'
    MaxStepSize: 0.4000

Review timing information for your simulation, such as when your simulation started and finished, and the time the simulation took to initialize, execute, and terminate.

simOut.getSimulationMetadata.TimingInfo
ans = 

  struct with fields:

          WallClockTimestampStart: '2016-06-17 10:26:58.433686'
           WallClockTimestampStop: '2016-06-17 10:26:58.620687'
    InitializationElapsedWallTime: 0.1830
         ExecutionElapsedWallTime: 1.0000e-03
       TerminationElapsedWallTime: 0.0030
             TotalElapsedWallTime: 0.1870

Add notes to your simulation.

simOut=simOut.setUserString('Results from simulation 1 of 10');
simOut.getSimulationMetadata
ans = 

  SimulationMetadata with properties:

        ModelInfo: [1×1 struct]
       TimingInfo: [1×1 struct]
    ExecutionInfo: [1×1 struct]
       UserString: 'Results from simulation 1 of 10'
         UserData: []

You can also add your own custom data using the UserData property.

Run-Button Simulations

For an interactive simulation, you can use set_param and get_param. With set_param and get_param, you can check the status of a running simulation and control how the simulation works by using block callbacks.

Control and Check Status of Simulation

This example shows how to use set_param to control the status of your simulation. set_param allows you to update the variables dynamically as well as write data-logging variables to the workspace.

Start a simulation.

set_param('vdp','SimulationCommand','start')

When you start a simulation using set_param and the 'start' argument, you must use the 'stop' argument to stop it. Not using the 'stop' argument causes the simulation to stop only once its finished.

Pause, continue, and stop a simulation.

set_param('vdp','SimulationCommand','pause')
set_param('vdp','SimulationCommand','continue')
set_param('vdp','SimulationCommand','stop')

When you use set_param to pause or stop a simulation, the simulation does not execute the commands immediately. You can use set_param to start a simulation after the stop command and to continue a simulation after the pause command. Simulink first completes uninterruptable work, such as solver steps and other commands that preceded the set_param command. Then, simulation starts, pauses, continues, or stops as specified by the set_param command.

Check the status of a simulation.

get_param('vdp','SimulationStatus')

The software returns 'stopped', 'initializing', 'running', 'paused', 'compiled', 'updating', 'terminating', or 'external' (used with the Simulink Coder™ product).

To update the changed workspace variables dynamically while a simulation is running, use the update command.

set_param('vdp','SimulationCommand','update')

Write all data-logging variables to the base workspace.

set_param('vdp','SimulationCommand','WriteDataLogs')

Automate Simulation Tasks Using Callbacks

A callback executes when you perform various actions on your model, such as starting, pausing, or stopping a simulation. You can use callbacks to execute a MATLAB script or other MATLAB commands. For more information, see Customize Model Behavior with Callbacks and Block Callbacks.

This example shows how to use the model StartFcn callback to automatically execute MATLAB code before the simulation starts.

Write a MATLAB script that finds Scope blocks in your model and opens them in the foreground when you simulate the model. Save the script in the current folder.

% openscopes.m 
% Brings scopes to forefront at beginning of simulation.

blocks = find_system(bdroot,'BlockType','Scope');

% Finds all of the scope blocks in the top level of your
	% model. To find scopes in subsystems, provide the subsystem
	% names. Type help find_system for more on this command.

for i = 1:length(blocks)
  set_param(blocks{i},'Open','on')
end

% Loops through all of the scope blocks and brings them
	% to the forefront.

Set the StartFcn parameter for the model to call the openscopes script.

set_param('my_model','StartFcn','openscopes')

See Also

| | | |

Related Topics