Is it possible to define a variable as static within a MATLAB MATLAB file?

121 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.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 13 Mar 2013
MATLAB normally works with automatic variables. An automatic variable is, in a sense, actually "created" each time the function is called. For example,
function auto()
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 )
persistent currentCount;
if nargin == 1
currentCount = initialize;
else
currentCount = currentCount + 1;
end
count = currentCount;
Below is a run of it:
clear all
counter
ans =
[]
counter(4)
ans =
4
counter
ans =
5
counter
ans =
6
counter(0)
ans =
0
counter
ans =
1
clear all
counter
ans =
[]

More Answers (0)

Categories

Find more on Function Creation in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!