Objects In Switch Statements

Evaluating the Switch Statement

MATLAB® enables you to use objects in switch and case statements if the object's class defines an eq method. The eq method implements the == operation on objects of that class.

For objects, switch_expression == case_expression defines how MATLAB evaluates switch and cases 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;
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
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.

Defining 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.

Implementation of eq

Here is a class that implements an eq method. Ensure 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 date and datestr functions return a character string with the name of the current day.

classdef WeeklyPlanner
   enumeration
      Monday, Tuesday, Wednesday, Thursday, Friday
   end
   methods (Static)
      function todaySchedule
         dayName = datestr(date,'dddd');
         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

Functions to Test Objects

These functions provide logical tests, which are useful when using objects in ordinary functions.

FunctionDescription
isa

Determine whether an argument is an object of specific class.

isequal

Determine if two objects are equal, which means both objects are of the same class and size and their corresponding property values are equal.

isobject

Determine whether input is a MATLAB object

Functions to Query Class Members

These functions provide information about object class members.

FunctionDescription
class

Return class of object.

enumeration

Display class enumeration members and names.

events

List event names defined by the class.

methods

List methods implemented by the class.

methodsview

List methods in separate window.

properties

List class property names.

Was this topic helpful?