Product Support
1903 - Command Line Functionality for Simulink
Introduction
Modification
Using Callbacks
Simulation
- Simulating from the MATLAB Command Prompt
- Using the SIM Command
- Using the SET_PARAM Command
- Using the MODEL Command
Introduction
Section 1: Introduction
Most tasks that can be done interactively in Simulink, including the ability to run repeated simulations, can be performed from the MATLAB command line without using the Simulink graphical user interface (GUI).
This technical note focuses on two common tasks that you can perform from the command line:
- Modification
- Simulation
Section 2: Getting Help
To learn more about functions used in this technical note, type the following at the MATLAB command prompt
help function_nameor
doc function_name
where function_name is the name of the function in question.
For a complete list of command line functions you can use to perform different tasks in Simulink, see the Programmatic Simulation section of the Using Simulink documentation.
Modification
Section 3: Modifying the Properties of a Simulink Diagram
You can query and/or modify the properties (parameters) of a Simulink diagram from the command line. Parameters that describe a model are known as model parameters, while parameters that describe a Simulink block are known as block parameters. Block parameters that are common to Simulink blocks are described as common block parameters. There are also block-specific parameters that are specific to particular blocks. Finally, there are mask parameters, which are parameters that describe a masked block.
The model and block properties also include callbacks, which are commands that are executed when a certain model or block event occurs. These events include opening a model, simulating a model, copying a block, opening a block, etc. For a list of all model and block properties, see the "Model and Block Parameters" section of the Block Libraries Simulink documentation.
Section 4: Getting Properties
To determine the values for properties, use the GET_PARAM command. The general syntax is
get_param('obj', 'parameter')
where obj is a system or block path name.
Use the following syntax to obtain all the parameters of a model or block:
get_param('obj', 'ObjectParameters')
The output is returned in a structure that describes obj parameters.
Example 1
The following commands get the attributes of the currently selected block's Name parameter.
p = get_param(gcb, 'ObjectParameters'); % Returns the output in a structure a = p.Name.Attributes
Example 2
This example displays the block types of all blocks in the mx + b system (the current system), described in the "Masked Subsystem Example" in the "Creating Masked Subsystems" section of the Using Simulink documentation.
blks = find_system(gcs, 'Type', 'block'); % Where gcs specifies the currently selected % system or subsystem listblks = get_param(blks, 'BlockType')
Example 3
The following command gets the dialog parameters of a Sine Wave block.
p = get_param('mymodel/Sine Wave', 'DialogParameters')
% Where mymodel is the model containing the Sine Wave block
Section 5: Setting Properties
You can modify a property using the SET_PARAM command. The general syntax is
set_param('obj', 'parameter1', value1, 'parameter2', value2, ...)
where obj is a system path, block path or zero (0). 0 is used to set the default value of a parameter or the
values of session parameters.
Note: Most block parameter values must be specified as strings. Two exceptions are the Position and UserData parameters, common to all blocks.
Example 1
The following command sets the Gain parameter of the Gain block
in mymodel to 1000.
set_param('mymodel/Gain', 'Gain', '1000')
Example 2
The command below sets the position of the Gain block in mymodel.
set_param('mymodel/Gain', 'Position', [50 100 110 120])
Example 3
This command sets the Gain parameter for a block in a masked subsystem. The variable k is associated
with the Gain parameter.
set_param('mymodel/Subsystem', 'k', '10')
Example 4
The following command sets the Amplitude, Frequency, and Phase parameters of a Sine Wave block to 10, 0.1 rad/sec, and pi respectively.
set_param(gcb,'amplitude', '10','frequency','0.1','phase','pi')
Using Callbacks
Section 6: What Are Callbacks?
Callbacks are a series of user-defined commands that get executed at a specified time. They define MATLAB expressions that execute when the block diagram or a block is acted upon in a particular way. Since they are model or block properties, you can use GET_PARAM and SET_PARAM to work with them. The Using Simulink documentation has a complete list of the model callbacks available in Simulink.
This section of the Technical Note will review four commonly used callback routines:
- PreLoadFcn
- OpenFcn
- CloseFcn
- StartFcn
Section 7: PreLoadFcn
The PreLoadFcn callback is executed when the model is first opened. For example, if you have a model that contains a Gain block with a gain specified as K, Simulink looks in the MATLAB base workspace for the variable K to be defined. By using the PreLoadFcn callback, K will automatically be defined every time the model is opened.
Assuming that you have several variables (such as K) predefined in an M-file called loadvar.m, to be used in a model called modelname.mdl, you can use the PreLoadFcn callback to execute the M-file loadvar.m. For example, type the following at MATLAB command prompt:
set_param('modelname','PreLoadFcn', 'loadvar')
After saving the model, every subsequent time you open this model, the loadvar function will execute. If you type
whos
at the MATLAB prompt after opening the modelname.mdl, you will see the variables from the loadvar.m declared in the MATLAB workspace.
Tip: If you want to call your model from an M-file without physically opening your model, you will need to first use the LOAD_SYSTEM function for the PreLoadFcn to be executed:
load_system('modelname')
Section 8: OpenFcn
The OpenFcn callback for a particular block is executed when you double-click the block. M-files can perform many different tasks, such as defining variables for a block, making a call to MATLAB to produce a plot of simulated data, or generating a GUI. The OpenFcn callback routine allows you to perform such tasks when a Simulink block is opened. This callback overrides the normal behavior that occurs when opening a block (when the parameter dialog box is displayed or a subsystem is opened). The following is an example on how to execute an M-file when double-clicking on a block.
Example:
Using your own small example model, single-click on the block to which you want to add an OpenFcn
property, thereby making it the "active" or "current" block. From the MATLAB command prompt type
set_param(gcb,'OpenFcn','expression')
where expression is a valid MATLAB command or an M-file that exists in your MATLAB search path. The test_opnfcn.mdlexample shows how to execute the change_gain.m M-file with the use of the OpenFcn callback when double-clicking on a subsystem.You will also need the setgain.m file. The command used to set up this callback routine is as follows:
set_param('test_opnfcn/Change_Gain','OpenFcn','change_gain')
Try the following:
- Copy the following files, available in the previous links, to your working directory:
- Open the model, test_opnfcn.
- Double-click on the change_gain subsystem. This should open a figure window.
- Change the value of the edit text box as desired to update the value of the Gain block.
- Run the simulation.
Section 9: CloseFcn
The CloseFcn callback is executed when a block diagram is closed. As shown in the example in the previous section, closing the model (test_opnfcn) also closed the figure window. You can use the CloseFcn callback routine to have your block perform similar actions. Here is an example:
set_param('test_opnfcn','CloseFcn','close all')
Section 10: StartFcn
The StartFcn callback is executed before the simulation starts. For example, you can use the StartFcn callback routine to make all of the Scope blocks within a Simulink model come to the forefront when opening the model. To do so, using the following code, create a simple M-file named openscopes.m, and save it on your MATLAB search path:
openscopes.m
% Brings scopes to forefront at beginning of simulation.
blocks = find_system(bdroot,'BlockType','Scope');
% Finds all of the scope blocks on the top level of your
% model. To find scopes in subsystems, give 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
After you have created this M-file, set the StartFcn for the model. For example:
set_param('modelname','StartFcn','openscopes')
Now, every time you run the model, all of the Scope blocks should open automatically and be in the forefront.
see the following Technical Support solutions on modifying models, getting or setting parameters, and using model callbacks:
- Is it possible to change the parameters of a block from the output of another block in Simulink?
- How do I load variables required in my Simulink model to the MATLAB workspace (as f14 does)?
- What is the command line syntax that unlinks a Simulink library block from my Simulink model?
- How do I create a popup control to set the mask block parameters in a masked subsystem in Simulink?
- How do I set a parameter of a masked subsystem from the parent masked subsystem?
- Is there a way to access the line information that connects every block in my Simulink model?
Simulation
Section 11: Simulating from the MATLAB Command Prompt
Entering simulation commands in the MATLAB Command Window or from an M-file enables you to run unattended simulations. This section will explain how simulation tasks can be done from the command line.
You can run a simulation from the command line using the following commands:
- SIM
- SET_PARAM
- MODEL (where MODEL is the name of a model)
Section 12: Using the SIM Command
The full syntax of the command that runs the simulation is:
[t,x,y] = sim('model_name', timespan, options, ut);
Only the model_name parameter is required. The timespan parameter specifies the simulation start and stop time. The options parameter is a structure that supplies additional simulation parameters, including the solver name and error tolerances. Parameters in the options structure are defined by using the SIMSET command. Parameters not supplied to the SIM command are taken from the Simulation Parameters dialog box settings. ut specifies optional external inputs to top-level Inport blocks. ut can be either a MATLAB function (expressed as a string) that specifies the input u = UT(t) at each simulation time step, a table of input values versus time for all input ports, or a comma-separated list of tables [ut1, ut2, ...], each of which corresponds to a specific port.
Example 1
This example simulates the model vdp for 1,000 seconds (the timespan), saving the last 100 rows
of the return variables. The simulation outputs the final 100 values for t and y only, and saves
the final state vector in a variable called xFinal.
[t,x,y] = sim('vdp', 1000, ...
simset('MaxRows', 100, 'OutputVariables', 'ty',...
'FinalStateName', 'xFinal'));
Example 2
This example simulates the vdp model for 2.5 seconds, producing outputs t, x, and y,
only at the times specified in a timespan of [0:0.001:2.5],and returns every other data logging
time point.
[t,x,y] = sim('vdp',[0:0.001:2.5],...
simset('Decimation',2,'OutputPoints','specified'));
Section 13: Using the SET_PARAM Command
You can change block parameter values in the workspace during a simulation and update the block diagram with these changes with the SET_PARAM command. This command lets you start, stop, pause, continue a simulation, or update a block diagram. The syntax of the SET_PARAM command for this use is
set_param('sys', 'SimulationCommand', 'cmd')
where sys is the name of the system and cmd is one of the following:
start stop pause continue update
Similarly, you can use the GET_PARAM command to check the status of a simulation. The syntax of the GET_PARAM command for this use is
get_param('sys', 'SimulationStatus')
Simulink returns is one of the following:
stopped initializing running paused updating terminating external (used with Real-Time Workshop)
Example
This example loads the vdp system, sets the Solver and StopTime parameters of the
system, and starts the simulation.
load_system('vdp')
set_param('vdp', 'Solver', 'ode15s', 'StopTime', '3000')
set_param('vdp','simulationcommand','start')
Note: The recommended way to run a simulation programmatically is to use the SIM command. However, the SIM command does not allow you to pause or stop the simulation until it has finished simulating. If you are using GUIs to start and stop your models, you should use the SET_PARAM command.
See the following Technical Support solutions on simulating from the command line.
- How do I stop a simulation in Simulink from the MATLAB command window?
- How do I run my Real-Time Windows Target simulation from the command line or an M-file?
- Is it possible to start and stop a Simulink simulation from inside a GUI?
- How do I stop a simulation from within an S-function?
Section 14: Using the MODEL Command
The model command is an alternative to SET_PARAM for running a simulation in stages. The MODEL command executes a specific phase of the simulation of a Simulink model whose name is model. This command is intended to allow linear analysis and other M-file program-based tools to run a simulation step by step; gathering information about the model's states and outputs at each step. The syntax for this command is as follows:
[sys,x0,str,ts] = model(t,x,u,flag); % where 'model' is the name of the model.
A detailed description of all the arguments you can use with the model command is found in the documentation.
Note: Use the model command if you want to write an M-file program that needs to examine intermediate results of a simulation. Use the SIM command if the program does not need to examine intermediate results.
Store