Multiple function "instances" of functions with persistent variables
12 views (last 30 days)
I think this is best shown using an abstract example:
function out = myFun(varIn,persIn)
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
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?