Wednesday, August 21, 2013

OOP Programming in MATLAB with stored values that also change (like an incrementer)

OOP Programming in MATLAB with stored values that also change (like an
incrementer)

I am relatively new to object-oriented programming in MATLAB, so maybe I
just don't understand the philosophy behind it, but I cannot seem to
figure this out. I want to have a set of object properties. One property
is statically created on object creation, and the other is an incrementing
value which stores information relevant to the object's use.
classdef MyClass
properties
max_inc; % Statically created cap on the incrementer
incr; % The incrementer
end
methods
% Constructor
function c = MyClass(set_max)
c.max_inc = set_max;
c.incr = 1;
end
% Function to do some stuff
function value = Next(c)
% Do some stuff
set(c, 'incr', c.incr + 1);
end
% Set function which is causing me trouble
function c = set.incr(c, value)
if(value <= c.max_inc)
c.incr = value;
else
c.incr = 1;
end
end
end
end
I was able to make a work-around which doesn't error out by getting rid of
the set function and implementing the Next(c) function as:
% Function to do some stuff
function value = Next(c)
% Do some stuff
curr_inc = c.incr;
if(curr_inc < c.max_inc)
c.incr = curr_inc + 1;
else
c.incr = 1;
end
end
While this runs, it does not actually seem to change the value of incr
when Next(c) is called (it always thinks incr is the starting value). I
don't want to make incr dependent because it does need to store its value
so I know how many times it has been incremented previously, and I cannot
make this a handle object because I need more than one to be active at the
same time (unless I am completely misunderstanding how handle objects
work). Is there not a way to do this? This seems like it should be a
really easy thing to do with an object.

No comments:

Post a Comment