How do you reset a persistent variable?

The documentaiton says that a persistent variable is reset when the function is cleared from memory. Why then do I not see the persistent variable update in the following?
fun(10)
y = 10
clear fun
fun(12)
y = 10
function fun(x)
persistent y
if isempty(y)
y=x;
end
y,
end

댓글 수: 5

Is function fun in its own m-file?
What does
which -all fun
return? Is there an aliased version perhaps?
Does rehash after the clear command make any difference?
I neither of the first two is the cause, then it would seem a bug. Which release?
I was/am in the middle of a debug session so didn't want to 'spearmint...
Matt J
Matt J 2022년 1월 14일
All code shown is in a single mfile. fun() is a local function.
dpb
dpb 2022년 1월 14일
편집: dpb 2022년 1월 14일
That's the problem...from the doc for clear the input description includes--
"Names of variables, scripts, functions, or MEX-functions to clear, specified as one or more character vectors or string scalars.
If name is a:
Function, then clear reinitializes any persistent variables in the function. Specifying a local or nested function is not supported. (emphasis added --dpb)
..."
Put fun in its own m-file and then retest.
Matt J
Matt J 2022년 1월 14일
Yep. Always read the fine print, I guess.
dpb
dpb 2022년 1월 14일
If you don't want to make fun an externally-visible function, then you'll have to have a flag variable and call the function with it to reset the persistent variable within the local function.
I have a bunch of short functions that set local working directories, etc., for specific workflows that use persistent variables to retain prior working directory and other key pieces on an 'EXIT' function...one of the pieces of those is the ability to reset those on demand. I hadn't thought of using clear for that purpose, though, with them as a shorthand invocation path.

댓글을 달려면 로그인하십시오.

 채택된 답변

Matt J
Matt J 2022년 1월 14일

0 개 추천

dpb 's answer resolved it..

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 File Operations에 대해 자세히 알아보기

질문:

2022년 1월 14일

댓글:

dpb
2022년 1월 14일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by