Is it possible to define a variable as static within a MATLAB MATLAB file?
233 views (last 30 days)
I would like my variable values to have persistent storage from one call of my MATLAB file to another or within subfunctions. I wish to know if there is an equivalent in MATLAB code to static variables in C subroutines.
MATLAB normally works with automatic variables. An automatic variable is, in a sense, actually "created" each time the function is called. For example,
a = 1
b = 2
Here, a and b will be "created" each time auto is called. As soon as auto is finished, these variables "disappear". This process happens automatically, hence the name automatic variables.
The value that an automatic variable has when a function finishes execution is guaranteed not to exist the next time the function is called.
A static variable, on the other hand, does NOT come and go as the function is called and returns. This implies that the value that a static variable has upon leaving a function will be the same value that variable will have the next time the function is called.
As of MATLAB 5.2, you can define a variable as persistent to give "static-like" behavior in your MATLAB file. Type "help persistent" for more information, or see the MATLAB 5.2 New Features Guide.
Note the following important characteristics of persistent variables in MATLAB:
1 - You can declare and use them within MATLAB file functions only.
2 - Only the function in which the variables are declared is allowed access to it.
3 - MATLAB does not clear them from memory when the function exits, so their value is retained from one function call to the next
Here is an example of a counter function that uses a persistent variable:
function count = counter( initialize )
if nargin == 1
currentCount = initialize;
currentCount = currentCount + 1;
count = currentCount;
Below is a run of it:
More Answers (1)
Noufal Thangal Rahim on 12 Jul 2019