MATLAB Object-Oriented Programming

(Joyce) #1

  • The default indexed reference behavior for scalar objects:


obj.Data(2,3)

ans =

5


  • And to add the functionality to index into the Data property with an expression like
    this statement:


obj(2,3)

If you redefine '()' indexing to support access to the Data property, you cannot create
arrays of MyDataClass objects and use '()' indexing to access individual objects. You
can reference only scalar objects.


To achieve the design goals, the subsref method must handle all indexing types. The
subsref method:



  • Calls the builtin subsref function for '.' indexing

  • Returns an error for '{}' indexing

  • Defines its own version of '()' indexing.


The result: obj(i) is equivalent to obj.Data(i).


function sref = subsref(obj,s)
% obj(i) is equivalent to obj.Data(i)
switch s(1).type
case '.'
sref = builtin('subsref',obj,s);
case '()'
if length(s) < 2
sref = builtin('subsref',obj.Data,s);
return
else
sref = builtin('subsref',obj,s);
end
case '{}'
error('MYDataClass:subsref',...
'Not a supported subscripted reference')
end
end


Class with Modified Indexing
Free download pdf