Best method to clear persistent variables
이전 댓글 표시
Hello all,
Recently I came to know that it is not a good idea to use
clear all;
So, I started using
clear variables
Now, I am wondering what I should do to clear only the persistent variables that I use inside my functions. It is absolutely critical that I clear the persistent states of my adaptive algorithms. Is there a way I can clear only persistent variables so that I don't have to re-run the entire script to generate the same data only to be used in a differently initialized algorithm?
Currently, I do this by calling the particular function with a
myfunction('init', init_method)
to clear the persistent variables or re-initialize them. Is it the best way? Your comments will help,
Thank you,
채택된 답변
추가 답변 (2개)
Walter Roberson
2011년 9월 26일
I don't know about the "best" way, but you can clear all the persistent variables in a particular function by asking to clear the function itself; e.g.,
clear myfunction
This will probably have the side effect of removing the stored JIT'd copy of it, causing it to be reparsed the next time it is invoked.
댓글 수: 6
Daniel
2014년 5월 23일
This worked perfectly, thanks!
Leo Simon
2014년 7월 14일
I spent many many hours today trying to track down a bug that was clearly related to a failure to clear a persistent variable. One of the most impenetrable bugs I've seen in a long time. Clearing the parent program whose child caused the problem fixed the problem. What an incredibly easy fix to a really nasty problem. Thanks very much!
Puneet Kumar
2018년 11월 16일
Not working for me
Walter Roberson
2018년 11월 16일
Puneet Kumar, please describe the difficulty in more detail.
Gavriel Aminov
2021년 1월 6일
편집: Walter Roberson
2022년 9월 4일
@Leo Simon,
Leo, you are right, that the problem must be solved at the parent of the calling function, I thank you.
I just want to stress the point, that I got the desirable result of clearing the persistent variable by the next way of:
clearing the function, the persistent variable is declared in, at the parent function of the calling function.
That is:
function FunParent()
clear FunWithPersistent
[a,b,c]=FunCalling();
end
------------------------------------
function FunCalling()
[x,y]=FunWithPersistent();
end
------------------------------------
function FunWithPersistent()
persistent OurHero
...
end
I'm sorry to say, that it is indeed seems to be a bug of MATLAB...
Dimitrios Patikas
2022년 9월 4일
Thank you
John D'Errico
2022년 9월 4일
You can also use
clear persistent
Which will clear all persistent variables.
카테고리
도움말 센터 및 File Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!