MATLAB: Making copies of functions with different workspaces

functionMATLABoopworkspace

How to call the same function in different workspaces?
I tried using handle but it doesn't work:
myaccum.m
function y = myaccum(x)
persistent buf;
if isempty(buf)
buf = 0;
end
buf = x + buf;
y = buf;
end
call.m
accum1 = @myaccum;
accum2 = @myaccum;
for i=1:10
out1(i) = accum1(2);
out2(i) = accum2(3);
end
display([out1; out2]);
Result:
>> call
2 7 12 17 22 27 32 37 42 47
5 10 15 20 25 30 35 40 45 50
Need:
>> call
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30

Best Answer

I recommend using a classdef, but this method using Nested Functions would also work:
function test
accum1 = getAccum;
accum2 = getAccum;
for i=1:10
out1(i) = accum1(2);
out2(i) = accum2(3);
end
disp([out1; out2]);
end
function h=getAccum
h=@myaccum;
buf=0;
function y = myaccum(x)
buf = x + buf;
y = buf;
end
end