MATLAB: Does subsequent/multiple runs produce different results when using S-function with the custom code in Simulink 8.0 (R2012b)

simulink

I have a custom C code, which I want to be used with S-function. After I build s-function, using S-function builder block, to create wrapper.c and .tlc files, I ran the model. The output is what I expected. After the model stopped, without changing anything, I click the run button again and the output of the model is different from the first time I ran the model.

Best Answer

With respect to this issue, following is the reason for the outputs to be different :
In your custom C code 'my_CustomCode.c' : lines
int j;
int debug_t[2];
are defined as global variables.
In the function call in the Custom Code:
int * my_CustomCode(int u, int v)
{
...
if (j==0)
{
...// Reset other global variables like : debug_t[]
j = 1;
}
...
}
The first time j=0 (is picked by default, i.e., global variable initialized to 0), and within this IF statement value of j is changed to 1, and thereafter all subsequent calls has j=1, hence skipping the IF statement.
This happens during the first Simulink run, now when the next Simulink run happens, value of j is still 1 and that means the IF statement which resets values for other variables is not run, and hence the simulation continues from there in the next run. Similarly, the variable global variable, debug_t[] uses the last run values and continue doing so.
The explaination for this behavior of MEX file:
".mex" files are DLLs and MEX file variables are only initialized when the ".mex" file is loaded, not with every simulation. Mex file loads only the first time the Simulink Model is run.
Only way to reset values if to execute the following command :
>> clear mex
before every Simulink run, to reload the Mex file everytime model is run. You can put this code in the InitFcn callback of the Simulink model.
The results you observe is due to a combined nature of Global variables with Mex files. As a recommendation, do not use global variables within your custom C code.