news:knip0i$q0c$1...@newscl01ah.mathworks.com...
Try:
classdef myValueClass
properties
val = [];
end
methods
function obj = timestwo(obj, in)
obj.val = 2 * in;
end
function v = double(obj)
v = obj.val;
end
end
end
y = myValueClass
y = timestwo(y, 5)
plot(y, 20, 'Marker', 'o', 'MarkerSize', 25)
You should see a circle at x = 10, y = 20. PLOT will try to call y's DOUBLE
method to convert it to a double and use the double precision result to
plot. You can see this by trying to PLOT something that can't be converted
into a double array, like:
plot({1, 2}, 5)
MATLAB doesn't know how to convert a cell array into a double, so it errors.
>> > As an aside, sometimes it seems like it would be nice to have the above
>> > syntax of a handle class, but be able to make independent copies of a
>> > given object like a value class... Anyone else think so?
>>
>> That's what matlab.mixin.Copyable is for.
>>
>>
http://www.mathworks.com/help/matlab/ref/matlab.mixin.copyableclass.html
>>
>
> Thanks Steve, I'll confess that I hadn't figured out the purpose of that
> abstract class yet! I think the fact that it was in the 'mixin' package
> threw me off, compared to the other abstract handle classes like
> hgsetget/dynamicprops which are not - I guess I figured from that fact &
> the package name that it had to do with defining a mixin class.
"mixin" is an object-oriented programming term, not something MathWorks
invented.
http://en.wikipedia.org/wiki/Mixin
If hgsetget and dynamicprops were introduced today, I suspect they might be
named matlab.mixin.hgsetget and matlab.mixin.dynamicprops or something
similar.
Some of the techniques from that article are possible in MATLAB. You can
inherit (which is how you'd use the matlab.mixin.* classes.) You can kind of
simulate adding a "method" to an instance by using a property to store a
function handle instead.
% begin myValueClass.m
classdef myValueClass
properties
val = [];
end
properties(Hidden)
todo = @dummy;
end
methods
function obj = timestwo(obj, in)
obj.val = 2 * in;
end
function v = double(obj)
v = obj.val;
end
end
end
function varargout = dummy(~, varargin)
[varargout{1:nargout}] = deal([]);
end
% end myValueClass.m
>> y = myValueClass;
>> y = y.timestwo(pi);
>> y.todo()
>> y.todo = @why;
>> y.todo()
To fool the tall good and smart system manager.
Is that a _good_ approach? Maybe not. But it is _an_ approach. Some of the
other approaches may also be possible; I didn't read through the whole list
in detail.