Multiple function "instances" of functions with persistent variables
21 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
D. Plotnick
le 7 Août 2019
Commenté : Walter Roberson
le 11 Août 2023
Hello all,
I think this is best shown using an abstract example:
function out = myFun(varIn,persIn)
persistent myPersistent
if isempty(myPersistent)
myPersistent = complicatedFunction(persIn);
disp('set')
else
disp('not')
end
out = anotherFun(varIn,myPersistent)
end
So, let us assume that complicatedFunction is kinda intensive and mostly redundant so I just want to calculate its output once, if I haven't already. The above function does this, and then uses the persistent variable myPersistent for its own operations. I track whether complicatedFunction ran using the 'set' and 'not' flags.
Now, let us say I actually want two copies of the above persistent function: I may want to initiate each with a different value of persIn and then select which to use externally. The aim is to do this without modifying myFun in any way (such as adding multiple persistent variables that are flagged on/off, saving two M-files with different names, or a bunch of other workarounds I can think of that do work: they are just messy).
I want something like:
f1 = @(x) myFun(x,value1)
f2 = @(x) myFun(x,value2)
v1 = feval(f1,x1)
v1 = feval(f1,x2)
v2 = feval(f2,x1)
Now, in my ideal world, I would get the returns
- Set
- Not
- Set
for the 3 function calls, since the first call to f1 sets the persistent, the second call uses that value and does not set it, and the third is to a different instance of the function, so it too needs to be set.
This doesn't happen [I get 'set'.'not','not'], and I can only assume that I am calling the same instace of myFun, and f1 and f2 are just handles to the same instance.
So, is there any way to do this?
Cheers,
-DP
0 commentaires
Réponse acceptée
Walter Roberson
le 7 Août 2019
2 commentaires
Walter Roberson
le 11 Août 2023
Someone asked me how to create independent persistent variables, so that the same function framework could be used with a number of independent counters.
The following solution does not use persistent variables, but it has the effect of being able to have independent counters.
c1 = gen_counter()
c2 = gen_counter();
c1(), c1(), c1()
c2(), c2()
c1()
c2()
function fh = gen_counter()
counter = 0;
fh = @count;
function out = count
counter = counter + 1;
out = counter;
end
end
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Whos dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!