Loren on the Art of MATLAB

Turn ideas into MATLAB


Loren on the Art of MATLAB has been archived and will not be updated.

Understanding Persistence

Questions about using persistent variables arise from time to time in the MATLAB newsgroup. Today I'd like to show you a little about what you might think you can do, but can't with persistent variables. I am also curious to hear from you about your use persistent variables, how often, and in what contexts. I personally now use nested functions exclusively (I think?) instead. Here are some links: blog article [1], blog article [2], the documentation.


First Sample Function

Here is the first of two sample functions that appear to be fairly similar. However, there are profound differences in the these functions, and only the first one will run in MATLAB.

type fcnPersist1
function q = fcnPersist1(u)
% fcnPersistent creates and uses a persistent variable.
persistent y;
if isempty(y)
    y = u;
    y = y+1;
q = y;

What you see is:

  • first the declaration that the variable y is persistent, followed by
  • some code to either initialize the persistent variable or to update its value, and
  • finally compute the desired output.

When I run mlint on this file, I find no messages. And when I run the code, I get no warning messages.

ans =


ans =


Second Sample Function

Here's the second sample function. In this function, you can see that I try to assign the persistent variable y to also be the output of the function. This is not allowed, and mlint does warn about us about this.

type fcnPersist2
function y = fcnPersist2(u)
% fcnPersist2 tries to create and use a persistent variable.
persistent y;
if isempty(y)
    y = u;
    y = y+1;

Here's on line of the mlint output:

  • 'y' appears to be incompatibly used or redefined.

This redefinition of y, as both an output variable and as a persistent variable, is prohibited in MATLAB and the result, as in the first example, must be assigned to another output variable.

  • print


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.