Documentation

Working with Enumerations

Basic Knowledge

The material presented in this section builds on an understanding of the information provided in the following sections.

 Defining Classes and Class Members

 Terminology and Concepts

Using Enumeration Classes

Create an enumeration class by adding an enumeration block to a class definition. For example, the WeekDays class enumerates a set of days of the week.

classdef WeekDays
   enumeration
      Monday, Tuesday, Wednesday, Thursday, Friday
   end
end

Constructing an Enumeration Member

Refer to an enumeration member using the class name and the member name:

ClassName.MemberName

For example, assign the enumeration member WeekDays.Tuesday to the variable today:

today = WeekDays.Tuesday;

today is a variable of class WeekDays:

whos
  Name       Size            Bytes  Class       Attributes

  today      1x1                56  WeekDays              

today

today = 

    Tuesday  

Default Methods

Enumeration classes have four methods by default:

methods(today)

Methods for class WeekDays:

WeekDays      char          eq            ne  
  • Default constructor (WeekDays in this case)

  • char — converts enumeration members to character strings

  • eq — enables use of == in expressions

  • ne — enables use of ~= in expressions

Equality and inequality methods enable you to use enumeration members in if and switch statements and other functions that test for equality.

Because you can define enumeration members with descriptive names, conversion to char is useful. For example:

today = WeekDays.Friday;
['Today is ',char(today)]
ans =

Today is Friday

Testing for Membership in a Set

Suppose you want to determine if today is a meeting day for your team. Create a set of enumeration members corresponding to the days on which the team has meetings.

today = WeekDays.Tuesday;
teamMeetings = [WeekDays.Wednesday WeekDays.Friday];

Use equality to determine if today is part of the teamMeetings set:

any(today == teamMeetings)
ans = 
     0

Using Enumerations in a Switch Statement

Enumerations work in switch statements:

function c = Reminder(day)
   % Add error checking here
   switch(day)
      case WeekDays.Monday
         c = 'Department meeting at 10:00';
      case WeekDays.Tuesday
         c = 'Meeting Free Day!';
      case {WeekDays.Wednesday WeekDays.Friday}
         c = 'Team meeting at 2:00';
      case WeekDays.Thursday
         c = 'Volley ball night';
   end
end

Pass a member of the WeekDays enumeration class to the Reminder function:

today = WeekDays.Wednesday;
Reminder (today)

ans =

Team meeting at 2:00

See Objects In Switch Statements for more information.

Getting Information About Enumerations

Obtain information about enumeration classes using the enumeration function. For example:

enumeration WeekDays

Enumeration members for class 'WeekDays':

    Monday
    Tuesday
    Wednesday
    Thursday
    Friday

See also Metaclass EnumeratedValues Property

Testing for an Enumeration

Use the isenum function to determine if a variable is an enumeration. For example:

today = WeekDays.Wednesday;
isenum(today)
ans =

     1

isenum returns true for empty enumeration objects:

noday = WeekDays.empty;
isenum(noday)
ans =

     1

You can also use the meta.class to determine if a variable's class is an enumeration class:

    today = WeekDays.Wednesday;
    mc = metaclass(today);
    mc.Enumeration
    ans =
    
         1

    Converting to Superclass Value

    If an enumeration class specifies a superclass, in many cases you can convert an enumeration object to the superclass by passing the object to the superclass constructor. However, the superclass must be able to accept its own class as input and return an instance of the superclass. MATLAB® built-in numeric classes, like double, single, and so on allow this conversion.

    For example, the Bearing class derives from the uint32 built-in class:

    classdef Bearing < uint32
       enumeration
          North (0)
          East  (90)
          South (180)
          West  (270)
       end
    end

    Assign the Bearing.East member to the variable a:

    a = Bearing.East;

    Pass a to the superclass constructor and return an object of the superclass, b:

    b = uint32(a); 
    whos
      Name      Size            Bytes  Class      Attributes
    
      a         1x1                60  Bearing              
      b         1x1                 4  uint32               

    The uint32 constructor accepts an instance of the subclass Bearing and returns and object of class uint32.

    Defining Methods in Enumeration Classes

    Define methods in an enumeration class like any MATLAB class. For example, here is the WeekDays class with a method called isMeetingDay added:

    classdef WeekDays
       enumeration
          Monday, Tuesday, Wednesday, Thursday, Friday
       end
       methods
          function tf = isMeetingDay(obj)
             tf = ~(WeekDays.Tuesday == obj);
          end
       end
    end

    Call isMeetingDay with an instance of the WeekDays class:

    today = WeekDays.Tuesday;
    today.isMeetingDay
    
    ans =
    
         0

    You can pass the enumeration member to the method directly:

    isMeetingDay(WeekDays.Wednesday)
    
    ans =
    
         1

    Defining Properties in Enumeration Classes

    Add properties to an enumeration class when you must store data related to the enumeration members. Set the property values in the class constructor. For example, the SyntaxColors class defines three properties whose values the constructor assigns to the values of the input arguments when you reference a class member.

    classdef SyntaxColors
       properties
          R
          G
          B
       end
       methods
          function c = SyntaxColors(r, g, b)
             c.R = r; c.G = g; c.B = b;
          end
       end
       enumeration
          Error   (1, 0, 0)
          Comment (0, 1, 0)
          Keyword (0, 0, 1)
          String  (1, 0, 1)
       end
    end

    When you refer to an enumeration member, the constructor initializes the property values:

    e = SyntaxColors.Error;
    
    e.R
    
    ans =
    
         1

    Because SyntaxColors is a value class (it does not derive from handle), only the class constructor can set property values:

    e.R = 0
    Setting the 'R' property of the 'SyntaxColors' class is not allowed.

    See Mutable (Handle) vs. Immutable (Value) Enumeration Members for more information on enumeration classes that define properties.

    Array Expansion Operations

    MATLAB enables assignment to any element of an array, even if the array does not exist. For example, you can create an array of WeekDays objects:

    classdef WeekDays
       enumeration
          Monday, Tuesday, Wednesday, Thursday, Friday
       end
    end
    clear
    ary(5) = WeekDays.Tuesday;

    MATLAB must initialize the values of array elements ary(1:4). The default value of an enumeration class is the first enumeration member defined by the class in the enumeration block. The result of the assignment to the fifth element of the array ary is, therefore:

    ary
    ary = 
    
        Monday       Monday       Monday       Monday       Tuesday  

    Constructor Calling Sequence

    Each statement in an enumeration block is the name of an enumeration member, optionally followed by an argument list. If the enumeration class defines a constructor, MATLAB calls the constructor to create the enumerated instances.

    MATLAB provides a default constructor for all enumeration classes that do not explicitly define a constructor. The default constructor creates an instance of the enumeration class:

    • Using no input arguments, if the enumeration member defines no input arguments

    • Using the input arguments defined in the enumeration class for that member

    For example, the input arguments for the Boolean class are 0 for Boolean.No and 1 for Boolean.Yes.

    classdef Boolean < logical
       enumeration
          No  (0)
          Yes (1)
       end
    end

    The values of 0 and 1 are of class logical because the default constructor passes the argument to the first superclass. That is,

    n = Boolean.No;

    results in a call to logical that is equivalent to the following statement in a constructor:

    function obj = Boolean(val)
       obj@logical(val)
    end

    MATLAB passes the member argument only to the first superclass. For example, suppose Boolean derived from another class:

    classdef Boolean < logical & MyBool
       enumeration
          No  (0)
          Yes (1)
       end
    end

    The MyBool class can add some specialized behavior:

    classdef MyBool
       methods 
          function boolValues = testBools(obj)
          ...
          end
       end
    end

    Now, the default Boolean constructor behaves as if defined like this function:

    function obj = Boolean(val)
       obj@logical(val) % Argument passed to first superclass constructor
       obj@MyBool       % No arguments passed to subsequent constructors
    end

    Restrictions Applied to Enumeration Classes

    Enumeration classes, which consist of a fixed set of possible values, restrict certain aspects of class use and definition:

    • Enumeration classes are implicitly Sealed. You cannot define a subclass of an enumeration class because doing so would expand the set.

    • You cannot call the constructor of an enumeration class directly. Only MATLAB can call enumeration class constructors to create the fixed set of members.

        Note:   It is possible to provide a conversion function in any class where the function is the name of an enumerated class and its purpose is to convert to the enumeration. It is possible to convert to an instance of an enumerated class (one of the defined set of members), but it is not possible to make a new instance of the class. See Default Converter for related information.

    • The properties of value-based enumeration classes are immutable. Only the constructor can assign property values. MATLAB implicitly defines the SetAccess attributes of all properties defined by value-based enumeration classes as immutable. You cannot set the SetAccess attribute to any other value.

    • All properties inherited by a value-based enumeration class that are not defined as Constant must have immutable SetAccess.

    • The properties of handle-based enumeration classes are mutable. You can set property values on instances of the enumeration class. See Mutable (Handle) vs. Immutable (Value) Enumeration Members for more information.

    • An enumeration member cannot have the same name as a property, method, or event defined by the same class.

    • Enumerations do not support colon (a:b) operations. For example, FlowRate.Low:FlowRate.High causes an error even if the FlowRate class derives from a numeric superclass.

    Techniques for Defining Enumerations

    Enumerations enable you to define names that represent entities useful to your application, without using numeric values or character strings. All enumerations support equality and inequality operations. Therefore, switch, if, and a number of comparison functions like isequal and ismember work with enumeration members.

    You can define enumeration classes in ways that are most useful to your application, as described in the following sections.

    Simple Enumerated Names

    Simple enumeration classes have no superclasses and no properties. These classes define a set of related names that have no underlying values associated with them. Use this kind of enumeration when you want descriptive names, but your application does not require specific information associated with the name.

    See the WeekDays class in the Using Enumeration Classes and the Defining Methods in Enumeration Classes sections.

    Enumerations with Built-In Class Behaviors

    Enumeration classes that subclass MATLAB built-in classes inherit most of the behaviors of those classes. For example, an enumeration class derived from the double class inherits the mathematical, relational, and set operations that work with variables of the class.

    Enumerations do not support the colon (:) operator, even if the superclass does. See Restrictions Applied to Enumeration Classes for more information.

    See Enumerations Derived from Built-In Types.

    Enumerations with Properties for Member Data

    Enumeration classes that do not subclass MATLAB built-in numeric and logical classes can define properties. These classes can define constructors that set each member's unique property values.

    The constructor can save input arguments in property values. For example, a Color class can specify a Red enumeration member color with three (Red, Green, Blue) values:

    enumeration
       Red (1,0,0)
    end

    See Enumerations That Encapsulate Data

    Was this topic helpful?