Guy on Simulink

Simulink & Model-Based Design

Tips and tricks when using the sim command

Today, I want to share a few tips and tricks about when and how to use the sim command.

The sim command vs. The Play Button

As you all know, there are two ways to simulate a model: using the play button, and using the sim command.

With the play button, you have the following advantages:

Those are very convenient when developing and debugging a model, but they come with a certain performance cost. In contrast, the sim command does not allow any of the above, allowing it to provide better performance.

Let's look at a few tips that might facilitate your workflow when using the sim command.

Monitoring the Progress of a simulation

When using sim and the model is not open in the editor, you have no idea how the simulation is progressing. My colleague Alex Trubitsyn just shared with me a trick to monitor the progress of the simulation started using sim: use a MATLAB timer. In its simplest version, the code looks like:

Using a timer to monitor the progress of a simulation

Use the Simulation Metadata

How many of you are measuring the time it takes for your simulation to run by using tic and toc around sim? Or by placing tic-toc statements in the model InitFcn and stopFcn callbacks?

With the simulation metadata, there is no need to do that anymore.

The Simulink.SimulationOutput object returned by sim contains a metadata field, which includes a TimingInfo sub-field. In this field, you can find timing for various phases of the simulation.

Timing info in simulation output

Tell sim to Capture Errors

Before R2016a, when a simulation through sim would error out, the logged data was lost and the script which invoked sim would stop. For those running long Monte-Carlo simulations overnight, you very likely ended up placing the sim command inside a try-catch statement.

In R2016a, I recommend passing the CaptureErrors parameter to sim. If the simulation errors out, sim will not, but instead will include the error message in the simulation metadata.

Capturing Errors

One of the main advantages of this technique is that the simulation output object will contain the logged data up to the error, allowing you to do some debugging without re-running the simulation.

Enable Timeout

If you are running multiple simulations in a loop and are using a variable-step solver, you probably want to use the timeout parameter of sim. That way, if for some reason one simulation hangs and begins to take unexpectedly small time steps, it will not block the other simulations for too long.

timeout

Now it's your turn

If you have other tricks facilitating the usage of the sim command, let us know by leaving a comment here.

|
  • print

댓글

댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.