MATLAB: How to work with static or global variables in CMEX S-functions? What are work vectors

%sfunctionglobalsfunctionsimulinkvectorswork

For example, I would like to track the previous value of each input signal element entering one of the ports of my S-function block. I would like to obtain this type of persistent storage of variables, and I wonder if I should use static or global variables. Doing this could lead to a reentrancy problem that I would like to avoid.

Best Answer

This enhancement has been incorporated in Release 2008a (R2008a). For previous product releases, read below for any possible workarounds:
Simulink has Work Vectors that you can allocate for storing static double, integer, and pointer variables. Work vectors allow you to create a reentrant S-function, and should be used instead of static or global variables. Work Vectors are discussed in detail with examples starting on page 7-24 of the Simulink 4.0 on-line version of the Writing S-functions Guide, available here:
To allocate storage, use the API macro ssSetNumXWork, where X could be: R for real, I for integer, or P for pointer. This is done in mdlInitializesizes.
Once allocated, you can then obtain these values using other macros, such as ssGetRWork, which returns a pointer to the allocated work vector.
This mechanism allows variables to be used in any function of the S-function, and assures the integrity of the variable, since calls between various functions using GLOBAL is not good practice.