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.

example

Examples

collapse all

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

Extended Capabilities

C/C++ Code Generation

Generate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

Version History

Introduced before R2006a