MATLAB Object-Oriented Programming

(Joyce) #1

end
end


Implement Addition for Object Data — double and plus


First, implement a double method that converts an object to an array of doubles. By
implementing a double converter method, it is possible to add a MyDataClass object to
another class of object. However, the other class must implement a double method that
also returns an array of doubles. For more information on type conversion, see “Object
Converters” on page 17-12.


Allow direct addition of the Data property values by implementing a plus method.
Implementing a plus method enables the use of the + operator for addition of
MyDataClass objects.


Because the plus method implements addition by adding double arrays, MATLAB:



  • Apply the rules of addition when adding MyDataClass objects

  • Returns errors for any condition that can cause errors in default numeric addition. For
    example, dimension mismatch.


The plus method uses the double method to convert the object to numeric values before
performing the addition:


function a = double(obj)
a = obj.Data;
end


function c = plus(obj,b)
c = double(obj) + double(b);
end


For example, the plus method enables you to add a scalar number to the object Data
array.


Here are the values of the Data, displayed using indexed reference:


obj(:,:)


ans =


8 9 3 9


Class with Modified Indexing
Free download pdf