Is it possible to define a variable as static within a MATLAB MATLAB file?
67 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
Akzeptierte Antwort
MathWorks Support Team
am 13 Mär. 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 =
[]
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Workspace Variables and MAT-Files finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!