How do you reset a persistent variable?

7 Ansichten (letzte 30 Tage)
Matt J
Matt J am 14 Jan. 2022
Kommentiert: dpb am 14 Jan. 2022
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 Kommentare
Matt J
Matt J am 14 Jan. 2022
Yep. Always read the fine print, I guess.
dpb
dpb am 14 Jan. 2022
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 14 Jan. 2022
dpb 's answer resolved it..

Weitere Antworten (0)

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by