persistent

Syntax

Description

persistent var1 ... varN declares variables var1 ... varN 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.

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)

Logging.

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)

Logging initial value.

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.