Multiple function "instances" of functions with persistent variables

12 views (last 30 days)
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);
out = anotherFun(varIn,myPersistent)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 7 Aug 2019
  1 Comment
D. Plotnick
D. Plotnick on 7 Aug 2019
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.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by