Guy on Simulink

Simulink & Model-Based Design

Handling Errors in Post Simulation Callbacks

Today I want to share a simple trick I recently recommended to a user who was struggling with retrieving error messages from simulations.

The Problem

What this user described is that, when simulating a model using the play button, if the model errors out, a clear error message is displayed in the Diagnostics Viewer:
However, when simulating the model using the sim command and a post-simulation function, the error was not as useful.
Here is a simplified version of the code simulating the model:
mdl = 'ex_modeling_simple_system';
in = Simulink.SimulationInput(mdl);
in = in.setPostSimFcn(@myPostSim);
out = sim(in,'ShowSimulationManager','on');
Where the post-simulation function adds to the SimulationOutput object additional post-processed information:
The error message is not very useful:
This same error message is also displayed in the Simulation Manager:

The Explanation

If you put a breakpoint in the post-simulation function, you will see that the "dot indexing" error is happening because the simulation errors out and the "logsout" field my code is trying to access does not exist.

The Solution

To avoid that, what I recommend is looking at the ErrorMessage field of the SimulationOutput object, and access the logged data only if there is no error:
That way, the Simulation Manager will display the original error:
This technique is especially useful if you are simulating the model on parallel workers using parsim, because it's not possible to interactively debug code running on parallel workers as I did here.

Now it's your turn

I would be curious to hear from you: should we implement such error handling around the post-simulation function to automatically return the actual simulation error instead of the post-simulation error when the simulation errors out?
Let us know in the comments below.
|
  • print

评论

要发表评论,请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。