MATLAB Object-Oriented Programming

(Joyce) #1

The result is:


SWITCH expression must be a scalar or string constant.


In this case, h1 is not scalar. Use isscalar to determine if an object is scalar before
entering a switch statement.


How to Define the eq Method


To enable the use of value-class objects in switch statements, implement an eq method
for the class. Use the eq method to determine what constitutes equality of two object of
the class.


Behave Like a Built-in Type


Some MATLAB functions also use the built-in == operator in their implementation.
Therefore, your implementation of eq should be replaceable with the built-in eq to enable
objects of your class work like built-in types in MATLAB code.


Design of eq


Implement the eq method to returns a logical array representing the result of the ==
comparison.


For example, the SwitchOnVer class implements an eq method that returns true for the
== operation if the value of the Version property is the same for both objects. In
addition, eq works with arrays the same way as the built-in eq. For the following
expression:


obj1 == obj2


The eq method works like this:



  • If both obj1 and obj2 are scalar, eq returns a scalar value.

  • If both obj1 and obj2 are nonscalar arrays, then these arrays must have the same
    dimensions, and eq returns an array of the same size.

  • If one input argument is scalar and the other is a nonscalar array, then eq treats the
    scalar object as if it is an array having the same dimensions as the nonscalar array.


Objects In Conditional Statements
Free download pdf