MATLAB: How to avoid using a global variable in this case

globalobjectoop

Dear all,
I have the following problem. I wrote some code where I overload various operators (+ – * /) and I would like to keep track of all the operations done. I initialize a session by creating a global variable, "myglobal", which will help me in this endeavor.
global myglobal
myglobal=containers.Map();
Then the typical overloaded operation does the following
function c=plus(a,b)
c=myobject(a.x+b.x);
push(c)
end
where the push function above roughly looks like this
function push(c)
global myglobal
Count=myglobal.Count+1;
myglobal(Count)=c.x;
end
I know using global variables is bad and I would like to get rid of the global variable. Any suggestion on how to go about this?
Thanks,
Pat.

Best Answer

Use a persistent variable instead:
function Reply = push(c)
persistent myCollector
if isempty(myCollector)
myCollector.Count = 0;
myCollector.Data = cell(1, 1000); % Pre-allocate
end
% Reply the local collector and reset it:
if nargin == 0
myCollector.Data = myCollector.Data(1:myCollector.Count); % Crop
Reply = myCollector;
myCollector = [];
return;
end
count = myCollector.Count+1;
myCollector.Data{count} = c.x;
myCollector.Count = count;
% Re-allocate on demand:
if length(myCollector.Data) == count;
myCollector.Data{count + 1000} = [];
end
end
This reduces the bad effects of letting the data cell grow in each iteration. The data are not stored globally, where any function can overwrite the values accidently. The value of the collector can be checked easily by the debugger in opposite to globals. And you can get the results by:
collector = push();
[EDITED] But when you look at this code, the persistenmt variable is actually a static member of an object oriented approach. When you do some oop already, it would be cleaner to implement this as further object also.