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.
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
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.
要发表评论，请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。