Control Simulations Programmatically

These examples show you how to use set_param and get_param to programmatically control a model simulation, check the status of a running simulation, and control simulations using block callbacks.

Control and Check Status of Simulation

This example shows how to use set_param to control and check the status of your simulation.

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 start, pause, continue or stop a simulation, the commands are requests for such actions and the simulation doesn't execute them immediately. 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).

Update changed workspace variables dynamically while a simulation is running.


Write all data-logging variables to the base workspace.


Automate Simulation Tasks Using Block 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.

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


Related Examples

Was this topic helpful?