sim

Simulate dynamic system

Description

simOut = sim(model) simulates the specified model using existing model configuration parameters, and returns the result as either a Simulink.SimulationOutput object (single-output format) or as a time vector compatible with Simulink version R2009a or earlier. See Backward-Compatible Syntax.

To return simulation results using the single-output format (simulation object), Single simulation output on the Data Import/Export pane of the Configuration Parameters dialog box is selected by default. This selection overrides the Dataset format used for signal logging.

To return simulation results using the backward-compatible format (time vector), see Backward-Compatible Syntax

simOut = sim(model,Name,Value) simulates the specified model using parameter name-value pairs.

example

simOut = sim(model,ParameterStruct) simulates the specified model using the parameter values specified in the structure ParameterStruct.

example

simOut = sim(model,ConfigSet) simulates the specified model using the configuration settings specified in the model configuration set ConfigSet.

example

simOut = sim(model,'ReturnWorkspaceOutputs','on') simulates the specified model using existing model configuration parameters, and returns the result as a Simulink.SimulationOutput object (single-output format).

simOut = sim(simIn) simulates a model using the inputs specified in the SimulationInput object, simIn . The sim command is also used with an array of SimulationInput objects to run multiple simulations in a series. If simIn is an array of Simulink.SimulationInput objects, output is returned as an array of Simulink.SimulationOutput objects.

Examples

Simulate Model with sim Command-Line Options in Structure

Simulate the model, vdp, in Rapid Accelerator mode for an absolute tolerance of 1e-5 and save the states in xoutNew and the output in youtNew.

Specify parameters using a name-value pairs structure paramNameValStruct for the sim command:

paramNameValStruct.SimulationMode = 'rapid';
paramNameValStruct.AbsTol         = '1e-5';
paramNameValStruct.SaveState      = 'on';
paramNameValStruct.StateSaveName  = 'xoutNew';
paramNameValStruct.SaveOutput     = 'on';
paramNameValStruct.OutputSaveName = 'youtNew';
simOut = sim('vdp',paramNameValStruct)
### Building the rapid accelerator target for model: vdp
### Successfully built the rapid accelerator target for model: vdp

Build Summary

Top model rapid accelerator targets built:

Model  Action                       Rebuild Reason                                    
======================================================================================
vdp    Code generated and compiled  Code generation information file does not exist.  

1 of 1 models built (0 models already up to date)
Build duration: 0h 0m 7.1872s
simOut = 
  Simulink.SimulationOutput:

                xoutNew: [65x2 double] 
                youtNew: [65x2 double] 

     SimulationMetadata: [1x1 Simulink.SimulationMetadata] 
           ErrorMessage: [0x0 char] 

Simulate Model with sim Command-Line Options in Configuration Set

Simulate the model, vdp, in Rapid Accelerator mode for an absolute tolerance of 1e-5 and save the states in xoutNew and the output in youtNew.

Specify parameters as name-value pairs in configuration set mdl_cs for the sim command:

mdl = 'vdp';
load_system(mdl)
simMode = get_param(mdl, 'SimulationMode');
set_param(mdl, 'SimulationMode', 'rapid')
cs = getActiveConfigSet(mdl);
mdl_cs = cs.copy;
set_param(mdl_cs,'AbsTol','1e-5',...
         'SaveState','on','StateSaveName','xoutNew',...
         'SaveOutput','on','OutputSaveName','youtNew')
simOut = sim(mdl, mdl_cs);
### Building the rapid accelerator target for model: vdp
### Successfully built the rapid accelerator target for model: vdp

Build Summary

Top model rapid accelerator targets built:

Model  Action                       Rebuild Reason                                    
======================================================================================
vdp    Code generated and compiled  Code generation information file does not exist.  

1 of 1 models built (0 models already up to date)
Build duration: 0h 0m 7.8027s
set_param(mdl, 'SimulationMode', simMode)

Simulate Model with Default Parameter Settings

Simulate the model vdp using default model configuration parameters.

simOut = sim('vdp','ReturnWorkspaceOutputs','on')

Input Arguments

collapse all

Name of model to simulate, specified as a character vector.

Example: simOut = sim('vdp')

Structure with fields that are the names of the configuration parameters for the simulation. The corresponding values are the parameter values.

Example: simOut = sim('vdp',paramNameValStruct)

The set of configuration parameters for a model.

Example: simOut = sim('vdp',mdl_cs)

SimulationInput object created by specifying the model name. For more information, see Simulink.SimulationInput.

Example: simIn = Simulink.SimulationInput('vdp')

Use the SimulationInput object to specify Block Parameters, Model Parameters, Variables and External Inputs to a model to be simulated.

Example: simIn = simIn.setBlockParameter('CSTR/Feed Temperature', 'Value', '300'); simIn = simIn.setModelParameter('StartTime', '1'); simIn = simIn.setVariable('FeedTemp0', 320)

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: 'Solver','ode15s','TimeOut','30' specifies that the model is simulated using the ode15s solver with a maximum simulation time of 30 seconds.

The sim command accepts all simulation parameters as name-value pair arguments.

In addition, the sim command accepts the following parameters that are not available on the Configset and set_param

By default, if an error occurs during simulation, the sim command stops and reports the error in the MATLAB Command Window. If you specify 'CaptureErrors','on', the sim command does not stop, but instead saves any errors to the ErrorDiagnostic structure within the SimulationMetadata object. The error message is saved in the ErrorMessage property of the SimulationOutput object.

This option is useful when running multiple simulations in a loop, so that one simulation error will not stop a script or function from continuing.

If you specify an array of input objects, the sim commands runs with CaptureErrors enabled. If an error occurs, the error messages are included in the Simulink.SimulationMetadata object for the simulation, as well as simulation data up to the point of the failure.

This option is not available for simulation in SIL and PIL modes.

Example: 'CaptureErrors','on'

(Rapid Accelerator mode only) Appends this suffix character vector to the filename of a model (before the file extension) if:

  • The model contains a To File block.

  • You call the sim command from parfor.

Example: 'ConcurrencyResolvingToFileSuffix','model'

Setting the value of 'Debug' argument to 'on'starts the simulation in debug mode (see Debugger Graphical User Interface for more information). The value of this option can be a cell array of commands to be sent to the debugger after it starts.

Example: 'Debug','on'

Use when you enable the LoggingToFile name-value pair for logging to persistent storage. Specify the destination MAT-file for data logging.

Tip

Do not use a file name from one locale in a different locale.

Example: 'LoggingFileName','out.mat'

Store logged data that uses Dataset format to persistent storage (MAT-file).

Use this feature when logging large amounts of data that can cause memory issues. For details, see Log Data to Persistent Storage.

Tip

To avoid running out of memory when accessing stored data, you can use a reference to access the object stored in the MAT-file. Use a Simulink.SimulationData.DatasetRef object to access stored data by reference. Using this object loads signal logging and states data into the model workspace incrementally (signal by signal). Accessing data for other kinds of logging loads all of the data at once.

Example: 'LoggingToFile','on'

(Rapid Accelerator mode only) Returns structure that contains run-time parameters for running Rapid Accelerator simulations in parfor.

Example: 'RapidAcceleratorParameterSets',parameterSet(idx)

(Rapid Accelerator mode only) Enables/disables up-to-date check. If you set this value to 'off', Simulink® does not perform an up-to-date check. It skips the start/stop callbacks in blocks. If you call the sim command from parfor, set this value to 'off'.

When you set this option to 'off', changes that you make to block parameter values in the model (for example, by using block dialog boxes, by using the set_param function, or by changing the values of MATLAB® variables) do not affect the simulation. Instead, use RapidAcceleratorParameterSets to pass new parameter values directly to the simulation.

Example: 'RapidAcceleratorUpToDateCheck','off'

Specifies the workspace in which to evaluate MATLAB expressions defined in the model. Setting SrcWorkspace has no effect on a referenced model that executes in Accelerator mode. Setting SrcWorkspace to current within a parfor loop causes a transparency violation.

Example: 'SrcWorkspace','current'

Specify the time, in seconds, to allow the simulation to run. If you run your model for a period longer than the value of TimeOut, the software issues a warning and stops the simulation. TimeOut refers to the time spent for a simulation.

Example: 'TimeOut',60

Enables simulation tracing facilities (specify one or more as a comma-separated list):

  • 'minstep' specifies that simulation stops when the solution changes so abruptly that the variable-step solvers cannot take a step and satisfy the error tolerances.

  • 'siminfo' provides a short summary of the simulation parameters in effect at the start of simulation.

By default, Simulink issues a warning message and continues the simulation.

Example: 'Trace','minstep','Trace','siminfo','Trace','compile'

Output Arguments

collapse all

Simulink.SimulationOutput object that contains all of the logged simulation results.

All simulation outputs (logged time, states, and signals) are returned in a single Simulink.SimulationOutput object. You define the model time, states, and output that is logged using the Data Import/Export pane of the Model Configuration Parameters dialog box. You can log signals using blocks such as the To Workspace and Scope blocks. The Viewers and Generators Manager can directly log signals.

Note

 The output of the sim command always returns to SimOut, the single simulation output object. The simulation output object in turn, is returned to the workspace.

More About

collapse all

Backward-Compatible Syntax

Starting with R2009b, the sim command was enhanced to provide greater compatibility with parallel computing. The improved single-output format saves all simulation results to a single object, simplifying the management of output variables.

For backward compatibility with R2009a or earlier releases, use the backward-compatible syntax:

[T,X,Y] = sim('model',Timespan, Options, UT)
[T,X,Y1,...,Yn] = sim('model',Timespan, Options, UT)

If you specify only the model argument, Simulink automatically saves the time, state, and output to the specified output arguments.

If you do not specify any output arguments, Simulink determines what data to log based on the settings for the Configuration Parameters > Data Import/Export pane. Simulink stores the simulation output either in the current workspace or in the variable ans, based on the setting for Save simulation output as a single object parameter.

Backward-Compatible Syntax Input and Output Arguments
ArgumentDescription
T

The time vector returned.

X

The state returned in matrix or structure format. The state matrix contains continuous states followed by discrete states.

Y

The output returned in matrix or structure format. For block diagram models, this variable contains all root-level blocks.

Y1,...,Yn

The outports, which can only be specified for diagram models. Here, n must be the number of root-level blocks. Each outport will be returned in the Y1,...,Yn variables.

'model'

The name of the model to simulate.

Timespan

The timespan can be TFinal, [TStart TFinal], or [TStart OutputTimes TFinal]. Output times are time points returned in T, but in general, T includes additional time points.

Options

Optional simulation parameters created in a structure by the simset command using name-value pairs.

UT

Optional external inputs. For supported expressions, see Load Data to Root-Level Input Ports.

Simulink requires only the model argument. Simulink takes all defaults from the block diagram, including unspecified options. If you specify any optional arguments, your specified settings override the settings in the block diagram.

Specifying an input argument of sim as the empty matrix, [ ], causes Simulink to use the default for that argument.

Backward-Compatible Syntax Examples

This command simulates the Van der Pol equations, using the vdp model. Set the ReturnWorkspaceOutputs to off before simulating the model.

set_param('vdp','ReturnWorkspaceOutputs','off');
[t,x,y] = sim('vdp')

This command simulates the Van der Pol equations, using the parameter values associated with the vdp model.

set_param('vdp','ReturnWorkspaceOutputs','off');
[t,x,y] = sim('vdp', [0 10]);

Tips

  • Parameters specified using the sim command override the values defined in the Model Configuration Parameters dialog box. The software restores the original configuration values at the end of simulation.

  • In the case of a model with a model reference block, the parameter specifications are applied to the top model.

  • When simulating a model with infinite stop time, to stop the simulation, you must press Ctrl+C. Ctrl+C breaks the simulation and the simulation results are not saved in the MATLAB workspace.

  • To specify the time span for a simulation, you must specify the StartTime and StopTime parameters.

  • To log the model time, states, or outputs, use the Data Import/Export pane of the Model Configuration Parameters dialog box.

  • To log signals, either use a block such as the To Workspace block or the Scope block, or use the Viewers and Generators Manager to log results directly.

  • To get a list of simulation parameters for the model vdp, in the MATLAB Command Window, enter:

    configSet = getActiveConfigSet('vdp')
    configSetNames = get_param(configSet, 'ObjectParameters')  

    This command lists several object parameters, including simulation parameters such as 'StopTime', 'SaveTime', 'SaveState', 'SaveOutput', and 'SignalLogging'.

Introduced before R2006a