How do I create efficient instance variable mutators in Matlab?
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 = calcV开发者_如何学Gool(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
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.
In this situation, you can give MATLAB an extra hint about what's going on by using the same name for your output as the input. In your example, this avoids creating a copy of obj
. This may not always be appropriate (for example, if you need both the old and new values of obj.pts
to update some other 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/ )
精彩评论