MATLAB Answers

0

Multiple function "instances" of functions with persistent variables

Asked by D. Plotnick on 7 Aug 2019
Latest activity Commented on by D. Plotnick on 7 Aug 2019
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
  1. Set
  2. Not
  3. 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 Comments

Sign in to comment.

1 Answer

Answer by Walter Roberson
on 7 Aug 2019
 Accepted Answer

  1 Comment

Brilliant: almost exactly what I was looking for, except that it is very unclear to me how this works with nested functions.
I put them into my test code, and ran it by memoizing the same functions that had been constructing my persistents, and everything worked fine. However, I had those functions nested within the code; no explicit variables being passed. To do the memoization (if I did it correctly), I had to explicitly pass the variables.
Again, this worked, but slowed down the execution considerably. Now, this may be on my implementation, or it may be that I cannot have my cake and eat it too.

Sign in to comment.