Main Content

sim

Simulate a Simulink model

Description

A Simulink® model represents a dynamic system. Simulating a model lets you understand the behavior of the system as a function of simulated time. The sim command uses the specified model and applies the arguments to the model. At the end of the simulation, the sim command reverts any arguments that it applied.

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

In the Data Import/Export pane of the Configuration Parameters dialog box,Single simulation output is selected by default. If the Single simulation output is not selected, the simulation results are returned as a time vector.

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.

simOut = sim(simIn) simulates the model using the inputs specified in the Simulink.SimulationInput object simIn . The sim command can be 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.

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.

Examples

Set Block Parameters using an Array of Simulink.SimulationInput Objects

This example modifies the block parameters of a model through the SimulationInput object.

Open the model.

openExample('simulink/OpenTheModelExample');
open_system('ex_sldemo_househeat');
load_system('ex_sldemo_househeat')

Create a SimulationInput object for this model.

mdl = 'sldemo_househeat';
in = Simulink.SimulationInput(mdl);

Modify block parameter.

in = in.setBlockParameter('sldemo_househeat/Set Point','Value','300');

Simulate the model.

out = sim(in)

Simulate Model with Default Parameter Settings

Simulate the model, vdp as it is in the present state, whether it is not loaded or is loaded and has some unsaved changes.

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

simOut = sim('vdp')

Simulate Model with sim Command-Line Options in Structure

Simulate the model, vdp, 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.SaveState      = 'on';
paramNameValStruct.StateSaveName  = 'xoutNew';
paramNameValStruct.SaveOutput     = 'on';
paramNameValStruct.OutputSaveName = 'youtNew';
simOut = sim('vdp',paramNameValStruct)
simOut = 
  Simulink.SimulationOutput:

                xoutNew: [64x2 double] 
                youtNew: [64x2 double] 

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

Simulate Model with sim Command-Line Options in Configuration Set

Simulate the model, vdp, 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)
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)
simOut = 
  Simulink.SimulationOutput:

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

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

Input Arguments

collapse all

Model to simulate, specified as a character vector.

Example: simOut = sim('vdp')

Structure containing parameter settings for the simulation specified as a structure. The fields in the structure are the names of the configuration parameters, and the corresponding values are the parameter values.

Set of configuration parameters for a model, specified as a Simulink.Configset object. For more information, see Simulink.ConfigSet.

Simulation input object for a model, specified as a Simulink.SimulationInput object created by specifying the model name. For more information, see Simulink.SimulationInput.

Use the SimulationInput object to specify Block Parameters, Model Parameters, Variables and External Inputs for simulation.

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

Name-Value 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 timeout that occurs when SIimulationTime reaches 30.

You can pass any model parameter and its value to the sim command.

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

Option to save errors to SimulationMetadata object, specified as 'off' or 'on'. 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 saves any errors to the ErrorDiagnostic structure within the SimulationMetadata object. The error message is saved in the ErrorMessage property of the SimulationOutput object.

When running multiple simulations in a loop, this option ensures 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'

Debug mode option for simulation, specified as 'off' or 'on'. 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'

This option is available in Rapid Accelerator mode only. Pre-simulation up-to-date-check, specified as 'on' or 'off'. 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. Use RapidAcceleratorParameterSets to pass new parameter values directly to the simulation.

Example: 'RapidAcceleratorUpToDateCheck','off'

Maximum simulation run time, specified as a positive scalar. 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

Simulation tracing facilities, specified as:

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

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

Fast restart option for simulation, specified as 'on'. Fast restart allows you to perform iterative simulations without compiling a model or terminating the simulation each time.

Output Arguments

collapse all

Simulation object containing logged simulation results, returned as a 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 select the data to be logged, such as 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. For more information on signal logging, see Signal Logging.

More About

collapse all

Backward-Compatible Syntax

Starting in 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 compatibility with R2009a or earlier releases, use this 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.

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 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 To Workspace block such as the To Workspace block or the Scope block, or use Signal Logging. For more information, see Export Signal Data Using Signal Logging.

  • 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