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:
- Pause, step forward and step backward using the Simulation Stepper
- Set conditional breakpoints on signals
- Tune parameters while the simulation is running
- Display port values for debugging
- You can interact with the MATLAB command prompt while the simulation is running
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:
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.
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.
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.
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.
评论
要发表评论,请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。