Making copies of functions with different workspaces

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

 Accepted Answer

Matt J
Matt J on 26 Aug 2020
Edited: Matt J on 26 Aug 2020
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

More Answers (1)

Make myaccum a class instead
classdef myaccum<handle %Must be put in myaccum.m
properties
buf=0;
end
methods
function y = increment(obj,x)
obj.buf=obj.buf+x;
y=obj.buf;
end
end
end
and then
accum1 = myaccum;
accum2 = myaccum;
for i=1:10
out1(i) = accum1.increment(2);
out2(i) = accum2.increment(3);
end
disp([out1; out2]);

1 Comment

Hello.
Both of these methods stop working as the nesting level increases.
for example
function [y1, y2, y3, y4] = fouraccum(x1, x2, x3, x4)
accum12 = @twoaccum;
accum34 = @twoaccum;
[y1, y2] = accum12(x1, x2);
[y3, y4] = accum34(x3, x4);
end
function [y1, y2] = twoaccum(x1, x2)
accum1 = myaccum;
accum2 = myaccum;
y1 = accum1.increment(x1);
y2 = accum2.increment(x2);
end
since every time the class is called
accum1 = myaccum;
the buf is reset

Sign in to comment.

Products

Release

R2019b

Community Treasure Hunt

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

Start Hunting!