views:

79

answers:

1

Previously, I implemented mutators as follows, however it ran spectacularly slowly on a recursive OO algorithm I'm working on, and I suspected it may have been because I was duplicating objects on every function call... is this correct?

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

I then tried implementing mutators without using the output object... however, it appears that in MATLAB i can't do this - the changes won't "stick" because of a scope issue?

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

For application purposes, an extremely simplified version of my code (which uses OO and recursion) is below.

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
+1  A: 

Matlab has two types of classes: handle and value.

A value class is passed by value, and has thus to be copied whenever you write to it. Also, method calls need to be of the form obj = method(obj); in order for the changes to 'stick'.

In contrast, handle objects are passed by reference, and thus, whenever you modify an object in any workspace - base workspace or a function's workspace - the object is changed everywhere. Thus, a call method(obj); changes obj in the calling workspace as well, even though obj is not returned explicitly.

The default class is the value object. If you want to use handle objects, your classdef line has to be:

classdef myslice < handle

i.e. you're subclassing the handle class.

Jonas