MATLAB: Why clear MEX needed

MATLABmemorymexsimulink

Hello Mathworks,
I am currently working with one Simulink model which has S-Function with .mexw64 file. Now when I run my model first time, I am getting correct result. But after than when ever I run Simulink model, the output is always zero. I have tried to check that after first Simulation, is there any new varible or anything which will be created that makes my output zero for every simulation after the first one?. But ther is not (I have checked that in MATLAB Workspace). Then when I use clear mex command in MATLAB and then tried to simulate the Simulink model 2nd time then it works. I dont know what exactly this command does? If it clears the mex then shouldnt it be in the workspace just like when we use command clearvars .. to clear specific variable?
If after 1st Simulation, MATLAB by default stores a memory to mex then where that can be seen? I mean what clears or delete clear mex command?
Any help would be appreciated.
Best Regard Jim

Best Answer

Does your S-Function use persistent variables? In C or C++ those correspond to any variable that is declared outside of any function. In C, persistent variables that are shared between compilation units would be declared "extern" in all compilation units except one; persistent variables that are local to the compilation unit would be declared "static".
When a mex function is run, it is loaded into memory, which includes allocating memory for all persistent variables; running the code leads to whatever changes to those variables made by executing the code. Initial loading can end up initializing a variable if the declaration of the variable has an initializer.
When you run the model again without having exited MATLAB and without having done "clear all" or "clear mex", then the function is not re-loaded. Persistent variables that had an initializer are not re-initialized in this case. The code will find the variables to have whatever state they had when the previous run finished.
"clear mex" causes the loaded mex function to be unloaded from memory. The next time the mex is run, it will not be present in memory and it will be loaded again, including initialization of persistent variables that had an initializer.
This behaviour of leaving persistent variables the same is not specific to MATLAB: it is the way C and C++ define persistent variables to work. It is a feature rather than a bug, since it permits hardware resource acquisition or authentication protocols to take place only once and be available for re-use when the code is executed again.
Note: if you re-create the .mex file during a session, then you should "clear mex" to force the new version to be used.