MATLAB: Are static variables in C or FORTRAN MEX S-functions not reset when running successive simulations

simulink

I am running a Simulink model which contains a C-MEX or FORTRAN S-function which uses persistent, static and/or global variables. When I run repeated (identical) simulation runs, I receive varying results due to S-function/C-code static variables not being re-initialized properly (except for the first time) by MATLAB and Simulink.

Best Answer

In general, work vectors are recommended over static or global variables if your S-function needs persistent memory storage. For more information on this, see the "Writing S-Functions" manual.
However, if you need to use such variables, you should be aware that C-MEX or FORTRAN S-functions are shared libraries and are not unloaded from memory when a simulation stops. There are multiple workaround to re-initialize these variables in an S-function.
1. You can clear all loaded MEX-functions (this includes but is not limited to S-functions) with the following command:
clear mex
You should run this command between simulations.
2. An alternative is to clear only those MEX-functions that should be unloaded from memory before a simulation because of their static variables. If the function that should be unloaded is mySfunction, you can unload it from memory with:
clear mySfunction
This option is used in the example model testmodel_wo1 and it is entered in the InitFcn callback of this model, such that this is called right before the model is simulated.
3. If you would like to use your custom S-function in various models and do not want to use model-wide callback functions, it is also possible to unload the S-function from memory in a callback specific to the S-function. You can set the following command as the InitFcn callback of the S-function itself:
clear(get_param(gcb, 'FunctionName'))
This option is used in the example model testmodel_wo2.
4. Finally it is also possible to initialize static variables in the S-function itself. In the example model testmodel_wo3, this option is used. For the example models attached to this solution, the Legacy Code Tool is used to generate the S-functions for the example models. For this option the StartFcnSpec is used to specify a C function that will be called at the start of a simulation. This function initializes persistent variables and since it will be called at the start of every simulation as opposed to when the S-function is loaded, it will have the same state for each simulation run.