Make "to workspace" variable available for StopFcn when using sim command
6 views (last 30 days)
Show older comments
Im my simulink model, I use "to workspace" blocks to output my results. After running the simulation, want to access the results within the "StopFcn" of the model. This is working when I run the model manually with the UI button (in the base workspace).
However, when I use the command "sim(gcm)" inside a function (function workspace), the results from the "to workspace" blocks are not available for the StopFcn and the function crashes.
I can get the results with simout=sim(gcm) an convert them to individual workspace variables, but then it is already too late for the StopFcn.
Who can help?
0 Comments
Answers (2)
NISARGA G K
on 22 Mar 2018
This is an unintended side-effect from some changes that happened in the R2015b release. Unfortunately there is no easy workaround that restores this functionality in R2015b and later releases. The Simulink model and the function that contains the "sim" command will likely need to be modified in order to work around the issue.
For instance if a user is executing a script from within a "StopFcn" callback that tries to access data in the function's workspace, the script should instead be executed in the function itself, right after executing the "sim" command
0 Comments
men8th
on 10 Feb 2023
I solved this by pulling the StopFcn callback into a standalone .m file, then wrapping the callback from the model with a try-catch block. Finally, when using the sim command, I used a Simulink.SimulationInput object and specified the callback as the postSimFcn associated with the object.
For example, in the model callback, use something like this:
try
RecircOrifice_StopFcn(simout);
catch
warning("StopFcn failed")
end
The above will execute the callback when the model is started using the GUI.
When using the sim command from the console, use something like this:
simIn = Simulink.SimulationInput("RecircOrifice");
simIn = simIn.setPostSimFcn(@(simout)RecircOrifice_StopFcn(simout));
clear simout
simout = sim(simIn);
In my case I'm using the callback to generate some charts. The above setup works regardless of how the model is executed (command line or using the GUI). Admittedly it's not very clean be but I think it's the best that can be done.
0 Comments
See Also
Categories
Find more on Model, Block, and Port Callbacks in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!