Documentation

我们为许可用户提供了部分翻译好的中文文档。您只需登录便可查阅这些文档

sim

Simulate dynamic system

Syntax

  • simOut = sim(model,Name,Value)
    example
  • simOut = sim(model,ParameterStruct)
    example
  • simOut = sim(model,ConfigSet)
    example
  • simOut = sim(model)
  • simOut = sim(model,'ReturnWorkspaceOutputs','on')
    example

Description

example

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.

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.

To return simulation results using the single-output format (simulation object), select Single simulation output on the Data Import/Export pane of the Configuration Parameters dialog box. 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.

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

Examples

Simulate Model with sim Command-Line Options

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 to the sim command:

simOut = sim('vdp','SimulationMode','rapid','AbsTol','1e-5',...
            'StopTime', '30', ...
            'ZeroCross','on', ...
            'SaveTime','on','TimeSaveName','tout', ...
            'SaveState','on','StateSaveName','xoutNew',...
            'SaveOutput','on','OutputSaveName','youtNew',...
            'SignalLogging','on','SignalLoggingName','logsout')
### Building the rapid accelerator target for model: vdp
### Successfully built the rapid accelerator target for model: vdp

Simulink.SimulationOutput:

       tout: [86×1 double]
    xoutNew: [86×2 double]
    youtNew: [86×2 double]

Use 'get' to access a variable by name.
Use 'getSimulationMetadata' to access metadata about the simulation.

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

Simulink.SimulationOutput:

    xoutNew: [65×2 double]
    youtNew: [65×2 double]

Use 'get' to access a variable by name.
Use 'getSimulationMetadata' to access metadata about the simulation.

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);
set_param(mdl, 'SimulationMode', simMode)
### Building the rapid accelerator target for model: vdp
### Successfully built the rapid accelerator target for model: vdp

Simulate Model with Default Parameter Settings

Simulate the model vdp using default model configuration parameters.

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

Related Examples

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)

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 single 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. See Model Parameters for a list of all simulation parameters.

In addition, the sim command accepts the following parameters.

collapse all

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.

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.

To view errors saved to the SimulationMetadata object, use the getSimulationMetadata method on a SimulationOutput object. For more information, see Simulink.SimulationMetadata.

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'

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 Using 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.SimlationData.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. See sim in parfor with Rapid Accelerator Mode.

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. See Transparency Violation for more details.

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.

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.

  • 'compile' displays the compilation phases of a block diagram model.

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 Signal & Scope Manager can directly log signals.

    Note:    The output of the sim command always returns to SimOut, the single simulation output object, not 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 Specify Data for 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. The command uses all default parameters.

[t,x,y] = sim('vdp')

This command simulates the Van der Pol equations, using the parameter values associated with the vdp model, but defines a value for the Refine parameter.

[t,x,y] = sim('vdp', [], simset('Refine',2));

This command simulates the Van der Pol equations for 1,000 seconds, saving the last 100 rows of the return variables. The simulation outputs values for t and y only, but saves the final state vector in a variable called xFinal.

[t,x,y] = sim('vdp', 1000, simset('MaxRows', 100, 
			'OutputVariables', 'ty', 'FinalStateName', 'xFinal'));

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.

  • 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 Signal and Scope 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


Was this topic helpful?