Main Content

sim

Simulate a万博1manbetxmodel

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. Thesimcommand uses the specified model and applies the arguments to the model. At the end of the simulation, thesimcommand reverts any arguments that it applied.

simOut= sim(model)simulates the specified model using existing model configuration parameters, and returns the result as aSimulink.SimulationOutputobject (single-output format).

In theData Import/Exportpane of theConfiguration Parametersdialog box,Single simulation outputis selected by default. If theSingle simulation outputis not selected, the simulation results are returned as a time vector.

To return simulation results using the backward-compatible format (time vector), seeBackward-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 theSimulink.SimulationInputobjectsimIn. Thesimcommand can be used with an array of模拟Inputobjects to run multiple simulations in a series. IfsimInis an array ofSimulink.SimulationInputobjects, output is returned as an array ofSimulink.SimulationOutputobjects.

example

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

example

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

Examples

collapse all

This example modifies the block parameters of a model through the模拟Inputobject.

Open the model.

openExample('simulink_general/sldemo_househeatExample')

Create a模拟Inputobject 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 the model,vdpas 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 outputis selected by default, sosimreturns the simulation results using the single-output format (simulation object). This selection overrides theDatasetformat used for signal logging.

simOut = sim('vdp')

Simulate the model,vdp, and save the states inxoutNewand the output inyoutNew.

Specify parameters using a name-value pairs structureparamNameValStructfor thesimcommand:

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 the model,vdp, for an absolute tolerance of1e-5and save the states inxoutNewand the output inyoutNew.

Specify parameters as name-value pairs in configuration setmdl_csfor thesimcommand:

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 aSimulink.Configsetobject. For more information, seeSimulink.ConfigSet.

模拟input object for a model, specified as aSimulink.SimulationInputobject created by specifying the model name. For more information, seeSimulink.SimulationInput.

Use the模拟Inputobject to specify Block Parameters, Model Parameters, Variables and External Inputs for simulation.

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

Name-Value Arguments

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, whereNameis the argument name andValueis the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and encloseNamein quotes.

Example:'Solver','ode15s','TimeOut','30'specifies that the model is simulated using the ode15s solver with a timeout that occurs whenSIimulationTimereaches 30.

You can pass any model parameter and its value to thesimcommand.

In addition, thesimcommand accepts the following parameters that are not available on theConfigsetandset_param

保存错误的选项模拟Metadata object, specified as 'off' or 'on'. By default, if an error occurs during simulation, thesimcommand stops and reports the error in the MATLAB®Command Window. If you specify'CaptureErrors','on',simcommand saves any errors to theErrorDiagnosticstructure within the模拟Metadataobject. The error message is saved in theErrorMessageproperty of the模拟Outputobject.

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, thesimcommands runs withCaptureErrorsenabled. If an error occurs, the error messages are included in theSimulink.SimulationMetadataobject 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 (seeDebugger Graphical User Interfacefor 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'

这个选项可以在快速Accelerator mode only. Pre-simulation up-to-date-check, specified as 'on' or 'off'. If you set this value to'off',S万博1manbetximulink不会执行最新检查。它在块中跳过开始/停止回调。如果您致电simcommand fromparfor, 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 theset_paramfunction, or by changing the values of MATLAB variables) do not affect the simulation. UseRapidAcceleratorParameterSetsto 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 ofTimeOut,software issues a warning and stops the simulation.TimeOutrefers to the time spent for a simulation.

Example:'TimeOut',60

模拟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.

Setting'StopOnError'to'on'stops the execution of simulations if an error is encountered.

Specifies the workspace in which to evaluate MATLAB expressions defined in the model. SettingSrcWorkspacehas no effect on a referenced model that executes in Accelerator mode. SettingSrcWorkspaceto current within aparforloop causes a transparency violation.

Example:'SrcWorkspace','current'

Output Arguments

collapse all

模拟object containing logged simulation results, returned as aSimulink.SimulationOutputobject that contains all of the logged simulation results.

All simulation outputs (logged time, states, and signals) are returned in a singleSimulink.SimulationOutputobject. You select the data to be logged, such as the model time, states, and output that is logged using theData Import/Exportpane of theModel Configuration Parametersdialog box. You can log signals using blocks such as theTo WorkspaceandScopeblocks. For more information on signal logging, seeSignal Logging.

More About

collapse all

Backward-Compatible Syntax

Starting in R2009b, thesimcommand was enhanced to provide greater compatibility with parallel computing. The improvedsingle-output formatsaves 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 themodelargument, 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 theConfiguration Parameters>Data Import/Exportpane. Simulink stores the simulation output either in the current workspace or in the variableans, based on the setting forSave simulation output as a single objectparameter.

Backward-Compatible Syntax Input and Output Arguments
Argument Description
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,nmust be the number of root-level blocks. Each outport will be returned in theY1,...,Ynvariables.

'model'

模型的名称要模拟。

Timespan

The timespan can beTFinal,[TStart TFinal], or[TStart OutputTimes TFinal]. Output times are time points returned inT, but in general,Tincludes additional time points.

Options

Optional simulation parameters created in a structure by thesimsetcommand using name-value pairs.

UT

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

Simulink requires only themodelargument. 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 ofsimas the empty matrix,[ ], causes Simulink to use the default for that argument.

Tips

  • Parameters specified using thesimcommand override the values defined in theModel Configuration Parametersdialog box. The software restores the original configuration values at the end of simulation.

  • In the case of a model with aModel块,应用于参数规范the top model.

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

  • To specify the time span for a simulation, you must specify theStartTimeandStopTimeparameters.

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

  • To log signals, either use aTo Workspaceblock such as theTo Workspaceblock or theScopeblock, or use Signal Logging. For more information, seeExport Signal Data Using Signal Logging.

  • To get a list of simulation parameters for the modelvdp, 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'.

Version History

Introduced before R2006a