MATLAB Object-Oriented Programming

(Joyce) #1

Specialize Subscripted Assignment — subsasgn


To support the equivalent of the indexed reference behavior with indexed assignment,
implement a subsasgn method.


  • Support the default indexed assignment:


obj.Data(2,3) = 9;


  • Add the functionality to assign values to the Data property with an expression like this
    statement:


obj(2,3) = 9;

Like the subsref method, the subsasgn method:


  • Calls the builtin subsasgn function for '.' indexing

  • Returns an error for '{}' indexing

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


The substruct function redefines the index type and index subscripts structure that
MATLAB passes to subsref and subsasgn.

function obj = subsasgn(obj,s,val)
if isempty(s) && isa(val,'MyDataClass')
obj = MyDataClass(val.Data,val.Description);
end
switch s(1).type
case '.'
obj = builtin('subsasgn',obj,s,val);
case '()'
if length(s)<2
if isa(val,'MyDataClass')
error('MyDataClass:subsasgn',...
'Object must be scalar')
elseif isa(val,'double')
% Redefine the struct s to make the call: obj.Data(i)
snew = substruct('.','Data','()',s(1).subs(:));
obj = subsasgn(obj,snew,val);
end
end
case '{}'
error('MyDataClass:subsasgn',...
'Not a supported subscripted assignment')

17 Specialize Object Behavior

Free download pdf