How to reset persistent variables in nested functions?
5 ビュー (過去 30 日間)
古いコメントを表示
I can't figure out whether this is a MATLAB bug or a PEBKAC issue, but in case of the latter, I figured I'd check here first.
I have a nested function with some persistent variables. Occasionally, when some condition is met in the outer function, I wish to be able to reset these variables to their initial state (i.e. [ ]). It doesn't seem to work to use "clear MyNestedFunc" in the outer function:
function MyFunc()
MyNestedFunc();
MyNestedFunc();
clear MyNestedFunc
MyNestedFunc();
function MyNestedFunc()
persistent foo
if isempty(foo)
foo = 1;
else
foo = foo + 1;
end
disp(foo)
end
end
My desired output from this is 1, 2, 1, but what I get is 1, 2, 3.
The way to do it so that it works is apparently to make foo a persistent variable in the outer function, but for reasons of code clarity and organization I'd really prefer to encapsulate it inside the nested function if I could.
Is this a MATLAB bug because "clear MyNestedFunc" doesn't have the expected effect, or am I trying to do something in the wrong way?
0 件のコメント
採用された回答
Matt Fig
2011 年 2 月 14 日
A hokey workaround:
function MyFunc()
resetfoo = false; % issued once at beginning.
MyNestedFunc();
MyNestedFunc();
MyNestedFunc();
resetfoo = true; % whenever we want to reset foo.
MyNestedFunc();
MyNestedFunc();
MyNestedFunc();
function MyNestedFunc()
persistent foo
if resetfoo || isempty(foo)
foo = 1;
resetfoo = false;
else
foo = foo + 1;
end
disp(foo)
end
end
その他の回答 (1 件)
Walter Roberson
2011 年 2 月 14 日
The documentation indicates somewhere that persistent variables are associated with the parsed version of file, not with the workspace, and are reset when the file as a whole is reloaded.
3 件のコメント
Walter Roberson
2011 年 2 月 14 日
This is a matter that I "read between the lines" from the description of "clear" and "rehash".
参考
カテゴリ
Help Center および File Exchange で Whos についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!