Objects in Conditional Statements
Enable Use of Objects in Conditional Statements
Enable the use of objects in conditional statements by defining relational operators for the class of the object. Classes that derive from the handle
class inherit relational operators. Value classes can implement operators to support the use of conditional statements involving objects. For information on defining operators for your class, see Operator Overloading.
How MATLAB Evaluates Switch Statements
MATLAB® enables you to use objects in switch
statements when the object’s class defines an eq
method. The eq
method implements the ==
operation on objects of that class.
For objects, case_expression
==
switch_expression
defines how MATLAB evaluates switch
and cases
statements.
The values returned by the eq
method must be of type logical
or convertible to logical
. MATLAB attempts to convert the output of eq
to a logical value if the output of the eq
method is a nonlogical value.
Note
You do not need to define eq
methods for enumeration classes. See Enumerations in Switch Statements.
Handle Objects in Switch Statements
All classes derived from the handle
class inherit an eq
method. The expression,
h1 == h2
is true
if h1
and h2
are handles for the same object.
For example, the BasicHandle
class derives from handle
:
classdef BasicHandle < handle properties Prop1 end methods function obj = BasicHandle(val) if nargin > 0 obj.Prop1 = val; end end end end
Create a BasicHandle
object and use it in a switch
statement:
h1 = BasicHandle('Handle Object');
h2 = h1;
Here is the switch
statement code:
switch h1 case h2 disp('h2 is selected') otherwise disp('h2 not selected') end
The result is:
h2 is selected
Object Must Be Scalar
The switch
statements work only with scalar objects. For example:
h1(1) = BasicHandle('Handle Object'); h1(2) = BasicHandle('Handle Object'); h1(3) = BasicHandle('Handle Object'); h2 = h1;
switch h1 case h2 disp('h2 is selected') otherwise disp('h2 not selected') end
The result is an error message.
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 objects 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 return 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 as follows:
If both
obj1
andobj2
are scalar,eq
returns a scalar value.If both
obj1
andobj2
are nonscalar arrays, then these arrays must have the same dimensions, andeq
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.
Implementation of eq
Here is a class that implements an eq
method. Ensure that your implementation contains appropriate error checking for the intended use.
classdef SwitchOnVer properties Version end methods function obj = SwitchOnVer(ver) if nargin > 0 obj.Version = ver; end end function bol = eq(obj1,obj2) if ~strcmp(class(obj1),class(obj2)) error('Objects are not of the same class') end s1 = numel(obj1); s2 = numel(obj2); if s1 == s2 bol = false(size(obj1)); for k=1:s1 if obj1(k).Version == obj2(k).Version bol(k) = true; else bol(k) = false; end end elseif s1 == 1 bol = scalarExpEq(obj2,obj1); elseif s2 == 1 bol = scalarExpEq(obj1,obj2); else error('Dimension missmatch') end function ret = scalarExpEq(ns,s) % ns is nonscalar array % s is scalar array ret = false(size(ns)); n = numel(ns); for kk=1:n if ns(kk).Version == s.Version ret(kk) = true; else ret(kk) = false; end end end end end end
Use SwitchOnVer
objects in switch
statements:
% Create known versions of objects ov1 = SwitchOnVer(1.0); ov2 = SwitchOnVer(2.0); ov3 = SwitchOnVer(3.0); ... ... if isscalar(objIn) switch(objIn) case ov1 disp('This is version 1.0') case ov2 disp('This is version 2.0') case ov3 disp('This is version 3.0') otherwise disp('There is no version') end else error('Input object must be scalar') end
Enumerations in Switch Statements
MATLAB enables you to use enumerations in switch
statements without requiring an explicitly defined eq
method for the enumeration class.
For example, the WeeklyPlanner
class defines enumerations for five
days of the week. The switch
/case
statements in
the todaySchedule
static method dispatch on the enumeration member
corresponding to the current day of the week. The datetime
,
day
, and string
functions return a string
containing the name of the current day.
classdef WeeklyPlanner enumeration Monday, Tuesday, Wednesday, Thursday, Friday end methods (Static) function todaySchedule dayName = string(day(datetime("name")); dayEnum = WeeklyPlanner.(dayName); switch dayEnum case WeeklyPlanner.Monday disp("Monday schedule") case WeeklyPlanner.Tuesday disp("Tuesday schedule") case WeeklyPlanner.Wednesday disp("Wednesday schedule") case WeeklyPlanner.Thursday disp("Thursday schedule") case WeeklyPlanner.Friday disp("Friday schedule") end end end end
Call todaySchedule
to display today’s schedule:
WeeklyPlanner.todaySchedule
Enumerations Derived from Built-In Types
Enumeration classes that derived from built-in types inherit the superclass eq
method. For example, the FlowRate
class derives from int32
:
classdef FlowRate < int32 enumeration Low (10) Medium (50) High (100) end end
The switchEnum
function switches on the input argument, which can be a FlowRate
enumeration value.
function switchEnum(inpt) switch inpt case 10 disp('Flow = 10 cfm') case 50 disp('Flow = 50 cfm') case 100 disp('Flow = 100 cfm') end end
Call switchEnum
with an enumerated value:
switchEnum(FlowRate.Medium)
Flow = 50 cfm