Main Content

Run Simulations Programmatically

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

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, control how the simulation works by using block callbacks.

Specify Parameter Name-Value Pairs

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

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

simOut = sim('vdp','SimulationMode','normal','AbsTol','1e-5',...
 'SaveFormat', 'Dataset');
outputs = simOut.get('yout')
outputs = 

  Package: Simulink.SimulationData

              Name: 'yout'
    Total Elements: 2

    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). The sim function does not return simulation values to the workspace.

Plot the output signal values against time.

plot(x1); hold on;
title('VDP States')
xlabel('Time'); legend('x1','x2')

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. Example syntax is shown below.

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

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.

Example syntax and resulting output for capturing errors with sim is:

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

  struct with fields:

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

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.

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 it's 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',...
 'SaveFormat', 'StructureWithTime');

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

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.

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.

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');
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.

Control and Check Status of Simulation

This example shows how to use set_param to control and check 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.


When you start a simulation using set_param and the 'start' argument, you must use the 'stop' argument to stop it.

Pause, continue, and stop a simulation.


When you use set_param to pause or stop a simulation, the commands are requests for such actions and the simulation doesn’t execute them 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.


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.


Write all data-logging variables to the base workspace.


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 Callbacks for Customized Model Behavior and Block Callback Parameters.

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)

% 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.


See Also

| | | |

Related Topics