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',...
            'SaveState','on','StateSaveName','xout',...
            'SaveOutput','on','OutputSaveName','yout',...
 'SaveFormat', 'Dataset');
outputs = simOut.get('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). The sim function does not return simulation values to the workspace.

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

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

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

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]

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',...
            'SaveState','on','StateSaveName','xoutNew',...
            'SaveOutput','on','OutputSaveName','youtNew',...
 'SaveFormat', 'StructureWithTime');

Access the ModelInfo property, which has some 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.

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.

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.

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

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 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)
  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