Main Content

Use Enumerated Data in Simulink Models

Enumerated data is data that is restricted to a finite set of values. An enumerated data type is a MATLAB® class that defines a set of enumerated values. Each enumerated value consists of an enumerated name and an underlying integer which the software uses internally and in generated code.

For basic conceptual information about enumerations in Simulink®, see Simulink Enumerations.

For information about generating code with enumerations, see Use Enumerated Data in Generated Code (Simulink Coder).

Define Simulink Enumerations

To define an enumerated data type that you can use in Simulink models, use one of these methods:

  • Define an enumeration class using a classdef block in a MATLAB file.

  • Use the function Simulink.defineIntEnumType. You do not need a script file to define the type. For more information, see the function reference page.

  • Use the function Simulink.importExternalCTypes to create a Simulink representation of an enumerated data type (enum) that your external C code defines.

Workflow to Define a Simulink Enumeration Class

Create Simulink Enumeration Class

To create a Simulink enumeration class, in the class definition:

  • Define the class as a subclass of Simulink.IntEnumType. You can also base an enumerated type on one of these built-in integer data types: int8, uint8, int16, uint16, int32, and uint32.

  • Add an enumeration block that specifies enumeration values with underlying integer values.

Consider the following example:

classdef BasicColors < Simulink.IntEnumType
  enumeration
    Red(0)
    Yellow(1)
    Blue(2) 
  end
end 

The first line defines an integer-based enumeration that is derived from built-in class Simulink.IntEnumType. The enumeration is integer-based because IntEnumType is derived from int32.

The enumeration section specifies three enumerated values.

Enumerated ValueEnumerated NameUnderlying Integer
Red(0)Red0
Yellow(1)Yellow1
Blue(2)Blue2

When defining an enumeration class for use in the Simulink environment, consider the following:

  • The name of the enumeration class must be unique among data type names and base workspace variable names, and is case-sensitive.

  • Underlying integer values in the enumeration section need not be unique within the class and across types.

  • Often, the underlying integers of a set of enumerated values are consecutive and monotonically increasing, but they need not be either consecutive or ordered.

  • For simulation, an underlying integer can be any int32 value. Use the MATLAB functions intmin and intmax to get the limits.

  • For code generation, every underlying integer value must be representable as an integer on the target hardware, which may impose different limits. See Configure a System Target File (Simulink Coder) for more information.

For more information on superclasses, see Convert to Superclass Value. For information on how enumeration classes are handled when there is more than one name for an underlying value, see How to Alias Enumeration Names.

Customize Simulink Enumeration

About Simulink Enumeration Customizations.  You can customize a Simulink enumeration by implementing specific static methods in the class definition. If you define these methods using the appropriate syntax, you can change the behavior of the class during simulation and in generated code.

The table shows the methods you can implement to customize an enumeration.

Static MethodPurposeDefault Value Without Implementing MethodCustom Return ValueUsage Context
getDefaultValueSpecifies the default enumeration member for the class.First member specified in the enumeration definitionA character vector containing the name of an enumeration member in the class (see Instantiate Enumerations)Simulation and code generation
getDescriptionSpecifies a description of the enumeration class.''A character vector containing the description of the typeCode generation
getHeaderFileSpecifies the name of a header file. The method getDataScope determines the significance of the file.''A character vector containing the name of the header file that defines the enumerated typeCode generation
getDataScopeSpecifies whether generated code exports or imports the definition of the enumerated data type. Use the method getHeaderFile to specify the generated or included header file that defines the type.'Auto'One of: 'Auto', 'Exported', or 'Imported'Code generation
addClassNameToEnumNamesSpecifies whether to prefix the class name in generated code.falsetrue or falseCode generation

For more examples of these methods as they apply to code generation, see Customize Enumerated Data Type (Simulink Coder).

Specify a Default Enumerated Value.  Simulink and related generated code use an enumeration's default value for ground-value initialization of enumerated data when you provide no other initial value. For example, an enumerated signal inside a conditionally executed subsystem that has not yet executed has the enumeration's default value. Generated code uses an enumeration's default value if a safe cast fails, as described in Type Casting for Enumerations (Simulink Coder).

Unless you specify otherwise, the default value for an enumeration is the first value in the enumeration class definition. To specify a different default value, add your own getDefaultValue method to the methods section. The following code shows a shell for the getDefaultValue method:

    function retVal = getDefaultValue()
      % GETDEFAULTVALUE Specifies the default enumeration member.
      % Return a valid member of this enumeration class to specify the default.
      % If you do not define this method, Simulink uses the first member.
      retVal = ThisClass.EnumName;
    end

To customize this method, provide a value for ThisClass.EnumName that specifies the desired default.

  • ThisClass must be the name of the class within which the method exists.

  • EnumName must be the name of an enumerated value defined in that class.

For example:

classdef BasicColors < Simulink.IntEnumType
  enumeration
    Red(0)
    Yellow(1)
    Blue(2) 
  end
  methods (Static)
    function retVal = getDefaultValue()
      retVal = BasicColors.Blue;
    end
  end
end 

This example defines the default as BasicColors.Blue. If this method does not appear, the default value would be BasicColors.Red, because that is the first value listed in the enumerated class definition.

The seemingly redundant specification of ThisClass inside the definition of that same class is necessary because getDefaultValue returns an instance of the default enumerated value, not just the name of the value. The method, therefore, needs a complete specification of what to instantiate. See Instantiate Enumerations for more information.

Save Enumeration in a MATLAB File

You can define an enumeration within a MATLAB file.

  • The name of the definition file must match the name of the enumeration exactly, including case. For example, the definition of enumeration BasicColors must reside in a file named BasicColors.m. Otherwise, MATLAB will not find the definition.

  • You must define each class definition in a separate file.

  • Save each definition file on the MATLAB search path. MATLAB searches the path to find a definition when necessary.

    To add a file or folder to the MATLAB search path, type addpath pathname at the MATLAB command prompt. For more information, see What Is the MATLAB Search Path?, addpath, and savepath.

  • You do not need to execute an enumeration class definition to use the enumeration. The only requirement, as indicated in the preceding bullet, is that the definition file be on the MATLAB search path.

Change and Reload Enumeration Classes

You can change the definition of an enumeration by editing and saving the file that contains the definition. You do not need to inform MATLAB that a class definition has changed. MATLAB automatically reads the modified definition when you save the file. However, the class definition changes do not take full effect if any class instances (enumerated values) exist that reflect the previous class definition. Such instances might exist in the base workspace or might be cached.

The following table explains options for removing instances of an enumeration from the base workspace and cache.

If In Base Workspace...If In Cache...

Do one of the following:

  • Locate and delete specific obsolete instances.

  • Delete everything from the workspace by using the clear command.

  • Delete obsolete instances by closing all models that you updated or simulated while the previous class definition was in effect.

  • Clear functions and close models that are caching instances of the class.

Similarly, if you defined an enumeration class by using Simulink.defineIntEnumType, you can redefine that class, using the same function, even if instances exist. However, you cannot change StorageType for the class while instances exist.

For more information about applying enumeration changes, see Automatic Updates for Modified Classes.

Import Enumerations Defined Externally to MATLAB

If you have enumerations defined externally to MATLAB that you want to import for use within the Simulink environment, you can do so programmatically with calls to one of these functions:

  • Simulink.defineIntEnumType — Defines an enumeration that you can use in MATLAB as if it is defined by a class definition file. In addition to specifying the enumeration class name and values, each function call can specify:

    • Character vector that describes the enumeration class.

    • Which of the enumeration values is the default.

    For code generation, you can specify:

    • Header file in which the enumeration is defined for generated code.

    • Whether the code generator applies the class name as a prefix to enumeration members — for example, BasicColors_Red or Red.

    As an example, consider the following class definition:

    classdef BasicColors < Simulink.IntEnumType
    	enumeration
    		Red(0)
    		Yellow(1)
    		Blue(2)
    	end
    	methods (Static = true)
    		function retVal = getDescription()
    			retVal = 'Basic colors...';
    		end
    		function retVal = getDefaultValue()
    			retVal = BasicColors.Blue;
    		end
    		function retVal = getHeaderFile()
    			retVal = 'mybasiccolors.h'; 
    		end
    		function retVal = addClassNameToEnumNames()
    			retVal = true;
    		end
    	end
    end

    The following function call defines the same class for use in MATLAB:

    Simulink.defineIntEnumType('BasicColors', ... 
         {'Red', 'Yellow', 'Blue'}, [0;1;2],...
         'Description', 'Basic colors', ...
         'DefaultValue', 'Blue', ...
         'HeaderFile', 'mybasiccolors.h', ...
         'DataScope', 'Imported', ...
         'AddClassNameToEnumNames', true);
    
  • Simulink.importExternalCTypes — Creates Simulink representations of enumerated data types (enum) that your existing C code defines.

If a MATLAB Function block in your model uses the enumerated type, configure the model configuration parameters to include (#include) the type definition from your external header file. See Control Imported Bus and Enumeration Type Definitions.

Permanently Store Enumerated Type Definition

Whether you define an enumeration by using a class file or by using the function Simulink.defineIntEnumType, you can permanently store the enumeration definition in a Simulink data dictionary. Models that are linked to the dictionary can use the enumeration. For more information, see Enumerations in Data Dictionary.

Simulate with Enumerations

Consider the following enumeration class definition — BasicColors with enumerated values Red, Yellow, and Blue, with Blue as the default value:

classdef BasicColors < Simulink.IntEnumType
  enumeration
    Red(0)
    Yellow(1)
    Blue(2)
  end
  methods (Static)
    function retVal = getDefaultValue()
      retVal = BasicColors.Blue;
    end
  end
end

Once this class definition is known to MATLAB, you can use the enumeration in Simulink and Stateflow® models. Information specific to enumerations in Stateflow appears in Enumerated Data (Stateflow). The following Simulink model uses the enumeration defined above:

The output of the model looks like this:

The Data Type Conversion block OrigToInt specifies an Output data type of int32 and Integer rounding mode: Floor, so the block converts the Sine Wave block output, which appears in the top graph of the Scope display, to a cycle of integers: 1, 2, 1, 0, 1, 2, 1. The Data Type Conversion block IntToColor uses these values to select colors from the enumerated type BasicColors by referencing their underlying integers.

The result is a cycle of colors: Yellow, Blue, Yellow, Red, Yellow, Blue, Yellow, as shown in the middle graph. The Enumerated Constant block EnumConst outputs Yellow, which appears in the second graph as a straight line. The Relational Operator block compares the constant Yellow to each value in the cycle of colors. It outputs 1 (true) when Yellow is less than the current color, and 0 (false) otherwise, as shown in the third graph.

The sort order used by the comparison is the numeric order of the underlying integers of the compared values, not the lexical order in which the enumerated values appear in the enumerated class definition. In this example the two orders are the same, but they need not be. See Specify Enumerations as Data Types and Enumerated Values in Computation for more information.

Specify Enumerations as Data Types

Once you define an enumeration, you can use it much like any other data type. Because an enumeration is a class rather than an instance, you must use the prefix ? or Enum: when specifying the enumeration as a data type. You must use the prefix ? in the MATLAB Command Window. However, you can use either prefix in a Simulink model. Enum: has the same effect as the ? prefix, but Enum: is preferred because it is more self-explanatory in the context of a graphical user interface.

Depending on the context, type Enum: followed by the name of an enumeration, or select Enum: <class name> from a menu (for example, for the Output data type block parameter) , and replace <class name>.

To use the Data Type Assistant, set the Mode to Enumerated, then enter the name of the enumeration. For example, in the previous model, the Data Type Conversion block IntToColor, which outputs a signal of type BasicColors, has the following output signal specification:

You cannot set a minimum or maximum value for a signal defined as an enumeration, because the concepts of minimum and maximum are not relevant to the purpose of enumerations. If you change the minimum or maximum for a signal of an enumeration from the default value of [], an error occurs when you update the model. See Enumerated Values in Computation for more information.

Get Information About Enumerated Data Types

The functions enumeration and Simulink.data.getEnumTypeInfo return information about enumerated data types.

Get Information About Enumeration Members

Use the function enumeration to:

  • Return an array that contains all enumeration values for an enumeration class in the MATLAB Command Window

  • Get the enumeration values programmatically

  • Provide the values to a Simulink block parameter that accepts an array or vector of enumerated values, such as the Case conditions parameter of the Switch Case block

Get Information About Enumerated Class

Use the function Simulink.data.getEnumTypeInfo to return information about an enumeration class, such as:

  • The default enumeration member

  • The name of the header file that defines the type in generated code

  • The data type used in generated code to store the integer values underlying the enumeration members

Enumeration Value Display

Wherever possible, Simulink displays enumeration values by name, not by the underlying integer value. However, the underlying integers can affect value display in Scope and Floating Scope blocks.

Block...Affect on Value Display...
ScopeWhen displaying an enumerated signal, the names of the enumerated values appear as labels on the Y axis. The names appear in the order given by their underlying integers, with the lowest value at the bottom.
Floating ScopeWhen displaying signals that are of the same enumeration, names appear on the Y axis as they would for a Scope block. If the Floating Scope block displays mixed data types, no names appear, and any enumerated values are represented by their underlying integers.

Enumerated Values with Non-Unique Integers

More than one value in an enumeration can have the same underlying integer value, as described in Specify Enumerations as Data Types. When this occurs, the value on an axis of Scope block output or in Display block output always is the first value listed in the enumerated class definition that has the shared underlying integer. For example:

Although the Enumerated Constant block outputs True, both On and True have the same underlying integer, and On is defined first in the class definition enumeration section. Therefore, the Display block shows On. Similarly, a Scope axis would show only On, never True, no matter which of the two values is input to the Scope block.

Instantiate Enumerations

Before you can use an enumeration, you must instantiate it. You can instantiate an enumeration in MATLAB, in a Simulink model, or in a Stateflow chart. The syntax is the same in all contexts.

Instantiating Enumerations in MATLAB

To instantiate an enumeration in MATLAB, enter ClassName.EnumName in the MATLAB Command Window. The instance is created in the base workspace. For example, if BasicColors is defined as in Create Simulink Enumeration Class, you can type:

bcy = BasicColors.Yellow

bcy = 

    Yellow

Tab completion works for enumerations. For example, if you enter:

bcy = BasicColors.<tab>

MATLAB displays the elements and methods of BasicColors in alphabetical order:

Double-click an element or method to insert it at the position where you pressed <tab>. See Code Suggestions and Completions for more information.

Casting Enumerations in MATLAB

In MATLAB, you can cast directly from an integer to an enumerated value:

bcb = BasicColors(2)

bcb = 

    Blue   

You can also cast from an enumerated value to its underlying integer:

>> bci = int32(bcb)

bci = 

    2   

In either case, MATLAB returns the result of the cast in a 1x1 array of the relevant data type.

Although casting is possible, use of enumeration values is not robust in cases where enumeration values and the integer equivalents defined for an enumeration class might change.

Instantiating Enumerations in Simulink (or Stateflow)

To instantiate an enumeration in a Simulink model, you can enter ClassName.EnumName as a value in a dialog box. For example, consider the following model:

The Enumerated Constant block EnumConst, which outputs the enumerated value Yellow, defines that value as follows:

You can enter any valid MATLAB expression that evaluates to an enumerated value, including arrays and workspace variables. For example, you could enter BasicColors(1), or if you had previously executed bcy = BasicColors.Yellow in the MATLAB Command Window, you could enter bcy. As another example, you could enter an array, such as [BasicColors.Red, BasicColors.Yellow, BasicColors.Blue].

You can use a Constant block to output enumerated values. However, that block displays parameters that do not apply to enumerated types, such as Output Minimum and Output Maximum.

If you create a Simulink.Parameter object as an enumeration, you must specify the Value parameter as an enumeration member and the Data type with the Enum: or ? prefix, as explained in Specify Enumerations as Data Types.

You cannot specify the integer value of an enumeration member for the Value parameter. See Enumerated Values in Computation for more information. Thus, the following fails even though the integer value for BasicColors.Yellow is 1.

The same syntax and considerations apply in Stateflow. See Enumerated Data (Stateflow) for more information.

Enumerated Values in Computation

By design, Simulink prevents enumerated values from being used as numeric values in mathematical computation, even though an enumerated class is a subclass of the MATLAB int32 class. Thus, an enumerated type does not function as a numeric type despite the existence of its underlying integers. For example, you cannot input an enumerated signal directly to a Gain block.

You can use a Data Type Conversion block to convert in either direction between an integer type and an enumerated type, or between two enumerated types. That is, you can use a Data Type Conversion block to convert an enumerated signal to an integer signal (consisting of the underlying integers of the enumerated signal values) and input the resulting integer signal to a Gain block. See Casting Enumerated Signals for more information.

Enumerated types in Simulink are intended to represent program states and control program logic in blocks like the Relational Operator block and the Switch block. When a Simulink block compares enumerated values, the values compared must be of the same enumerated type. The block compares enumerated values based on their underlying integers, not their order in the enumerated class definition.

When a block like the Switch block or Multiport Switch block selects among multiple data signals, and any data signal is of an enumerated type, all the data signals must be of that same enumerated type. When a block inputs both control and data signals, as Switch and Multiport Switch do, the control signal type need not match the data signal type.

Casting Enumerated Signals

You can use a Data Type Conversion block to cast an enumerated signal to a signal of any numeric type, provided that the underlying integers of all enumerated values input to the block are within the range of the numeric type. Otherwise, an error occurs during simulation.

Similarly, you can use a Data Type Conversion block to cast a signal of any integer type to an enumerated signal, provided that every value input to the Data Type Conversion block is the underlying integer of some value in the enumerated type. Otherwise, an error occurs during simulation.

You cannot use a Data Type Conversion block to cast a numeric signal of any non-integer data type to an enumerated type. For example, the model used in Simulate with Enumerations needed two Data Conversion blocks to convert a sine wave to enumerated values.

The first block casts double to int32, and the second block casts int32 to BasicColors. You cannot cast a complex signal to an enumerated type regardless of the data types of its real and imaginary parts.

Casting Enumerated Block Parameters

You cannot cast a block parameter of any numeric data type to an enumerated data type. For example, suppose that an Enumerated Constant block specifies a Value of 2 and an Output data type of Enum: BasicColors:

An error occurs because the specifications implicitly cast a double value to an enumerated type. The error occurs even though the numeric value corresponds arithmetically to one of the enumerated values in the enumerated type.

You cannot cast a block parameter of an enumeration to any other data type. For example, suppose that a Constant block specifies a Constant value of BasicColors.Blue and an Output data type of int32.

An error occurs because the specifications implicitly cast an enumerated value to a numeric type. The error occurs even though the enumerated value's underlying integer is a valid int32.

See Also

| |

Related Topics