How to create efficient mutators of instance variables in Matlab?

I previously implemented mutators as follows, however it ran spectacularly slow on the recursive OO algorithm I am working on, and I suspected it might be because I was duplicating objects on every function call ... is that correct?

%% Example Only
obj2 = tripleAllPoints(obj1)
    obj.pts = obj.pts * 3;
    obj2 = obj1
end

      

Then I tried to implement mutators without using the output object ... however, it looks like in MATLAB I can't do that - won't the changes "stick" due to the scope problem?

%% Example Only
tripleAllPoints(obj1)
    obj1.pts = obj1.pts * 3;
end

      

An extremely simplified version of my code (which uses OO and recursion) is shown for application purposes.

classdef myslice

properties
    pts     % array of pts
    nROW % number of rows
    nDIM % number of dimensions
    subs    % sub-slices
end % end properties

methods
    function calcSubs(obj)
        obj.subs = cell(1,obj.nROW);
        for i=1:obj.nROW
            obj.subs{i} = myslice;
            obj.subs{i}.pts = obj.pts(1:i,2:end);
        end
    end

    function vol = calcVol(obj)
      if obj.nROW == 1
         obj.volume = prod(obj.pts);
      else
         obj.volume = 0;
         calcSubs(obj);
         for i=1:obj.nROW
                obj.volume = obj.volume + calcVol(obj.subs{i});
         end
      end
    end

end % end methods

end % end classdef

      

+2


a source to share


2 answers


Matlab has two types of classes: descriptor and value .

The value class is passed by value and thus copied whenever you write to it. In addition, method calls must be in the form obj = method(obj);

in order for changes to be "bound".

In contrast, descriptor objects are passed by reference, and therefore whenever you change an object in any workspace β€” the base workspace or the workspace of a function β€” the object changes everywhere. Thus, the call method(obj);

modifies the call obj

workspace even if it is obj

not explicitly returned.



The default class is a value object. If you want to use handle objects your string classdef

should be:

classdef myslice < handle

      

i.e. you subclass the handle class.

+4


a source


In this situation, you can give MATLAB an additional hint of what's going on by using the same name for your output as the input. In your example, this allows you to create a copy obj

. This may not always be appropriate (for example, if you need both the old and the new value to obj.pts

update another property).

%% Example Only
obj = tripleAllPoints(obj)
    obj.pts = obj.pts * 3;
end

      



(see also: http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data/ )

+1


a source







All Articles