persistent - Define persistent variable - MATLAB (original) (raw)
Define persistent variable
Syntax
Description
persistent var1 ... varN
declares the specified variables as persistent. Persistent variables are local to the function in which they are declared, yet their values are retained in memory between calls to the function. Code at the MATLAB® command line and in other functions cannot change persistent variables.
When MATLAB first encounters a particular persistent
statement, it initializes the persistent variable to an empty matrix ([]
).
MATLAB clears persistent variables when you clear or modify a function that is in memory. To keep a function in memory, use mlock.
Examples
Count Calls to Function
Create the function myFun
in your current working folder. Each time you call the function, the value ofn
increases.
function myFun() persistent n if isempty(n) n = 0; end n = n+1 end
At the command prompt, call myFun
three times.
Clear myFun
and call it another two times. Clearing the function also clears the persistent variable.
Log Data at Specified Time Interval
Write a function that logs data if at least three seconds have passed since the last log entry. Define logTime
as a persistent variable that stores the last time logData
wrote to the file.
In a file in your current working folder, define the logData
function.
function logData(fname,n) persistent logTime currTime = datetime;
if isempty(logTime)
logTime = currTime;
disp('Logging initial value.')
dlmwrite(fname,n)
return
end
dt = currTime - logTime;
if dt > seconds(3)
disp('Logging.')
dlmwrite(fname,n,'-append')
logTime = currTime;
else
disp(['Not logging. ' num2str(seconds(dt)) ' sec since last log.'])
end
end
At the command prompt, call logData
in a loop. The loop has 10 iterations, and each iteration takes approximately 1 second. Therefore, MATLAB writes 4 values to myLog.txt
(at approximately 0, 3, 6, and 9 seconds).
for n = 1:10 pause(1) logData('myLog.txt',rand) end
Logging initial value. Not logging. 1.005 sec since last log. Not logging. 2.009 sec since last log. Logging. Not logging. 1.007 sec since last log. Not logging. 2.013 sec since last log. Logging. Not logging. 1.005 sec since last log. Not logging. 2.007 sec since last log. Logging.
Call the logData
function again to append another value.
logData('myLog.txt',rand)
Clear the logData
function to reinitialize the persistent variable. Call the logData
function again. This time, the function overwrites myLog.txt
instead of appending a value.
clear logData logData('myLog.txt',rand)
Tips
- Persistent variables are similar to global variables because MATLAB creates permanent storage for both. They differ from global variables because persistent variables are known only to the function that declares them. Therefore, code at the MATLAB command line or other functions cannot change persistent variables.
- Since MATLAB initializes a persistent variable to an empty matrix (
[]
), typically functions check to see if a persistent variable is empty, and, if so, initialize it.
function myFun()
persistent n
if isempty(n)
n = 0;
end
n = n+1;
end - The declaration of a variable as persistent must precede any other references to the variable, including input or output arguments. For example, the
persistent
declarations in the following functions are invalid.
function myfunA(x)
persistent x
end
function myfunB
x = 0;
persistent x
end - To clear a persistent variable, use clear with the name of the function that declares the variable. For example,
clear myFun
.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
- Persistent variables in the generated code do not share values with MATLAB.
- Every generated MEX function has its own copy of persistent data. Each invocation of a particular MEX function reuses values from prior invocations.
- In a Simulink® model, each MATLAB Function (Simulink) block contains its own copy of persistent data. If a MATLAB function that contains a persistent variable is called from two different blocks, the model has two persistent variables. Also, each run of the simulation creates a new copy of the persistent data.
- In the MATLAB code intended for code generation, a persistent variable
p
must be assigned beforep
is used. The only exception is a check usingisempty(p)
that can be performed before assignment. You can use this check to make sure thatp
is assigned before it is used in your MATLAB code. - If the parent function declares a persistent variable, the function must assign the variable before it calls a nested function that uses the persistent variable.
- Persistent variables cannot be renamed in generated code. See Reuse the Same Variable with Different Properties (MATLAB Coder).
- The body of a parfor (MATLAB Coder)-loop cannot contain a persistent variable declaration.
- The generated code does not enforce order of evaluation in expressions. For most expressions, the order of evaluation is not significant. However, for expressions with side effects, the generated code can produce the side effects in different order from the original MATLAB code. Expressions that produce side effects include those that modify persistent variables. See Differences Between Generated Code and MATLAB Code (MATLAB Coder).
- A handle object that a persistent variable refers to must be a singleton object. See Handle Object Limitations for Code Generation (MATLAB Coder).
- The code generator computes class initial values at class loading time before code generation. If you use persistent variables in MATLAB class property initialization, the value of the persistent variable that is computed when the class loads belongs to MATLAB. It is not the value that is used at code generation time.
In particular, if you use coder.target (MATLAB Coder) in a MATLAB class property initialization,coder.target('MATLAB')
returnstrue
.
See MATLAB Classes Definition for Code Generation (MATLAB Coder).
Version History
Introduced before R2006a