Main Content

persistent

Define persistent variable

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.

example

Examples

collapse all

Create the function myFun in your current working folder. Each time you call the function, the value of n increases.

function myFun()
    persistent n
    if isempty(n)
        n = 0;
    end
    n = n+1
end

At the command prompt, call myFun three times.

myFun
myFun
myFun
n =

     1


n =

     2


n =

     3

Clear myFun and call it another two times. Clearing the function also clears the persistent variable.

clear myFun
myFun
myFun
n =

     1


n =

     2

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

    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

Version History

Introduced before R2006a