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 , blog article , 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.
function q = fcnPersist1(u) % fcnPersistent creates and uses a persistent variable. persistent y; if isempty(y) y = u; else y = y+1; end 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 = 4 ans = 5
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.
function y = fcnPersist2(u) % fcnPersist2 tries to create and use a persistent variable. persistent y; if isempty(y) y = u; else y = y+1; end
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.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.