MATLAB: Can I save and restore persistent variables in Embedded MATLAB across simulations in Simulink

emlpersistencesimulinkstates

I have some persistent variables in my Embedded MATLAB block in the model. I would like to be able to save and restore the values of this persistent variable over successive simulations.

Best Answer

It is possible to do this using the SimState save and restore feature for the Embedded MATLAB block. The persistent variable values gets saved into the entire model's SimState if the option 'Save Complete SimState in Final State' is checked in the model's configuration parameters. The attached example model and MATLAB file illustrate this behavior. The SimState from the first simulation gets saved as xFinal which is a SimState snapshot at time t = 3s. The following command outputs the value of the persistent variable 'buffer' from the Embedded MATLAB block:
xFinal.getBlockSimState('test1_tmw/EML').buffer
The second simulation starts from time t = 3s and uses xFinal as the initial state.