Making copies of functions with different workspaces
Show older comments
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
More Answers (1)
Matt J
on 26 Aug 2020
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
Slava Razumov
on 6 Oct 2020
Categories
Find more on Automated Fixed-Point Conversion in MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!