MATLAB Object-Oriented Programming

(Joyce) #1

[varargout{1:nargout}] = builtin('subsref',obj,s);
end
otherwise
error('Not a valid indexing expression')
end


Using varargout for the returned value enables the method to work with object arrays.
For example, suppose that you want to support the return of a comma-separated list with
an expression like this one:


[x1,...xn] = objArray.PropertyName(Indices)


This expression results in a two-element indexing structure array. The first-level type is
dot ('.') and the second level is parentheses ('()'). Build the varargout cell array
with each value in the array.


case '.'
...
if length(s)==2 && strcmp(s(2).type,'()')
prop = s(1).subs; % Property name
n = numel(obj); % Number of elements in array
varargout = cell(1,n); % Preallocate cell array
for k = 1:n
varargout{k} = obj(k).(prop).(s(2).subs);
end
end
...
end


subsasgn Pattern


The following framework for the subsasgn method shows how to use the indexing
structure in conditional statements that implement assignment operations.


function obj = subsasgn(obj,s,varargin)
switch s(1).type
case '.'
if length(s) == 1
% Implement obj.PropertyName = varargin{:};
...
elseif length(s) == 2 && strcmp(s(2).type,'()')
% Implement obj.PropertyName(indices) = varargin{:};
...
else
% Call built-in for any other case
obj = builtin('subsasgn',obj,s,varargin{:});
end
case '()'
if length(s) == 1


Code Patterns for subsref and subsasgn Methods
Free download pdf