Hello!
I have a class with one field 'x':
=======================================
classdef MyTestClass
properties
x
end % properties
methods
function obj = MyTestClass
obj.x = [];
end
end % methods
end % classdef MyTestClass
=======================================
This class can be used like this:
t = MyTestClass;
t.x = [5 6 7 8];
t.x(2:3)
t is object scalar and t.x is matrix. How make t seems as matrix of objects and t.x as scalar of double? But really need store t as object scalar and t.x is matrix. For example:
t = MyTestClass;
t.x = [5 6 7 8];
t(2:3).x % gets x(2:3)
[n m] = size(t); % same as и [n m] = size(t.x);
t2 = t(2:3) % get object of MyTestClass with values t2.x == t.x(2:3)
It's need to overload subsref method and intercept calls of "object(indexes).x" to "object.x(indexes)", but methods' call "[a b c ...] = object.method(x, y, z, ...)" also works too. I did that by next way:
=======================================
classdef MyTestClass
properties
x
end % properties
methods
function obj = MyTestClass
obj.x = [];
end
function varargout = size(obj, varargin)
varargout{1:nargout} = size(obj.x, varargin{:});
end
function varargout = subsref(obj, S)
if length(S) == 1 && strcmp(S(1).type, '()')
% обращение типа function(obj(indexes))
varargout{1} = MyTestClass;
varargout{1}.x = builtin('subsref', obj.x, S(1));
elseif length(S) > 1 && strcmp(S(1).type, '()')
% обращение типа obj(indexes).field
tmp = MyTestClass;
tmp.x = builtin('subsref', obj.x, S(1));
if nargout > 0
varargout{1:nargout} = builtin('subsref', tmp, S(2:end));
else
builtin('subsref', tmp, S(2:end));
end
else
if nargout > 0
varargout{1:nargout} = builtin('subsref', obj, S);
else
builtin('subsref', obj, S);
end
end
end
end % methods
end % classdef MyTestClass
=======================================
Let's see:
=======================================
clear
t = MyTestClass;
t.x = [5 6 7 8];
y = t.x + 5
t(1:2) % OK, gets object with values [5 6]
t(1:2).x % Wrong! Don't show values at command window
t.x(1:2) % Wrong! Don't show values at command window
size(t) % OK
[n m] = size(t) % Wrong!
t.size % Wrong! Don't show values at command window
s = t.size % OK
[n m] = t.size % Wrong! Same error when [n m] = size(t)
=======================================
What a correct implementation of subsref method? Source code of "double" and other basic classes are not avaible.
|