Use Enumerated Data in Generated Code - MATLAB & Simulink (original) (raw)

Enumerated Data Types

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.

This MATLAB class definition defines an enumerated data type namedBasicColors.

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

For basic information about enumerated data types and their use in Simulink® models, see Use Enumerated Data in Simulink Models. For information about enumerated data types in Stateflow® charts, see Define Enumerated Data Types (Stateflow).

Choose Approach for Defining Enumerated Data Types

These approaches are available for defining an enumerated data type:

This table lists a sampling of enumerated data type definition conditions and requirements and for each one identifies recommended approaches.

Condition or Requirement classdef block MATLAB file. Simulink.defineInEnumType Function Simulink.importExternalCTypes Function
Define data type definition in a MATLAB script file. X
Extend data type definitions by adding content such as methods, callbacks, properties, and other custom information. X
Derive definition from a base class X
Store multiple data type definitions in one file. X
Change data type definitions across multiple execution runs within a single MATLAB session without incurring negative effects X
Use existing data type definitions that are in an external C header file. X

For more information about the approaches, see Use Enumerated Data in Simulink Models and relevant function reference pages

Specify Integer Data Type for Enumeration

When you specify a data type for your enumeration, you can:

You can specify these integer data types:

Use a Class Definition in a MATLAB File

To specify an integer data type size, derive your enumeration class from the integer data type.

classdef Colors < int8 enumeration Red(0) Green(1) Blue(2) end end

The code generator generates this code:

typedef int8_T Colors;

#define Red ((Colors)0) #define Green ((Colors)1) #define Blue ((Colors)2)

Use the Function Simulink.defineIntEnumType

To specify an integer data type size, specify the name-value pairStorageType as the integer data type.

Simulink.defineIntEnumType('Colors',{'Red','Green','Blue'},... [0;1;2],'StorageType','int8')

The code generator generates this code:

typedef int8_T Colors;

#define Red ((Colors)0) #define Green ((Colors)1) #define Blue ((Colors)2)

Customize Enumerated Data Types

When you generate code from a model that uses enumerated data, you can implement these static methods to customize the behavior of the type during simulation and in generated code:

The first of these methods, getDefaultValue, is relevant to simulation and code generation, and is described in Specify a Default Enumerated Value. The other methods are relevant only to code generation. To customize the behavior of an enumerated type, include a version of the method in the methods(Static) section of the enumeration class definition. If you do not want to customize the type, omit themethods(Static) section. The table summarizes the methods and the data to supply for each one.

Static Method Purpose Default Value Without Implementing Method Custom Return Value
getDefaultValue Specifies the default enumeration member for the class. First member specified in the enumeration definition A character vector containing the name of an enumeration member in the class (see Instantiate Enumerations).
getDescription Specifies a description of the enumeration class. '' A character vector containing the description of the type.
getHeaderFile Specifies 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 type.By default, the generated#include directive uses the preprocessor delimiter" instead of < and>. To generate the directive #include <myTypes.h>, specify the custom return value as'<myTypes.h>'.
getDataScope Specifies 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' 'Auto', 'Exported', or'Imported'
addClassNameToEnumNames Specifies whether to prefix the class name in generated code. false true or false
isTunableInCode Specifies whether enumerated values are tunable in generated code. false true or false

Specify a Description

If you have an Embedded Coder® license, you can enable the Simulink data object descriptions model configuration parameter to include descriptions for enumerated data types in the generated code. To specify a description for an enumerated data type, include this method in themethods(Static) section of the enumeration class:

function retVal = getDescription() % GETDESCRIPTION Optional description of the data type. retVal = 'description'; end

Substitute a MATLAB character vector for description. The generated code that defines the enumerated type includes the specified description.

Import Type Definition in Generated Code

To prevent generated code from defining an enumerated data type, which allows you to provide the definition in an external file, include these methods in themethods(Static) section of the enumeration class:

function retVal = getHeaderFile()
  % GETHEADERFILE Specifies the file that defines this type in generated code.
  % The method getDataScope determines the significance of the specified file.
  retVal = 'imported_enum_type.h';
end

function retVal = getDataScope()
  % GETDATASCOPE Specifies whether generated code imports or exports this type.
  % Return one of:
  % 'Auto':     define type in model_types.h, or import if header file specified
  % 'Exported': define type in a generated header file
  % 'Imported': import type definition from specified header file
  % If you do not define this method, DataScope is 'Auto' by default.
  retVal = 'Imported';
end

Instead of defining the type in_`model`__types.h, which is the default behavior, generated code imports the definition from the specified header file by using an#include statement like:

#include "imported_enum_type.h"

The code generator does not create the imported header file. You must provide the header file by using the file name specified by the methodgetHeaderFile, which defines the enumerated data type.

To create a Simulink enumeration that corresponds to your existing C-code enumeration, use theSimulink.importExternalCTypes function.

When you import an enumerated type definition, you can set up the enumerated values to be tunable in generated code. For more information see Configure Enumerated DataTypes for Tunability in Generated Code.

Export Type Definition in Generated Code

To generate a separate header file that defines an enumerated data type, include these methods in the methods(Static) section of the enumeration class:

function retVal = getDataScope()
  % GETDATASCOPE Specifies whether generated code imports or exports this type.
  % Return one of:
  % 'Auto':     define type in model_types.h, or import if header file specified
  % 'Exported': define type in a generated header file
  % 'Imported': import type definition from specified header file
  % If you do not define this method, DataScope is 'Auto' by default.
  retVal = 'Exported';
end

function retVal = getHeaderFile()
  % GETHEADERFILE Specifies the file that defines this type in generated code.
  % The method getDataScope determines the significance of the specified file.
  retVal = 'exported_enum_type.h';
end

Generated code exports the enumerated type definition to the generated header fileexported_enum_type.h.

Add Prefixes To Class Names

By default, enumerated values in generated code have the same names that they have in the enumeration class definition. Alternatively, your code can prefix every enumerated value in an enumeration class with the name of the class. You can use this technique to prevent identifier conflicts or to improve the readability of the code. To specify class name prefixing, include this method in the methods(Static) section of an enumeration class:

function retVal = addClassNameToEnumNames()
  % ADDCLASSNAMETOENUMNAMES Specifies whether to add the class name
  % as a prefix to enumeration member names in generated code.
  % Return true or false.
  % If you do not define this method, no prefix is added.
  retVal = true;
end

Specify the return value as true to enable class name prefixing or as false to suppress prefixing. If you specify true, each enumerated value in the class appears in generated code as_EnumTypeNameEnumName_. For the example enumeration classBasicColors in Enumerated Data Types, the data type definition in generated code might look like this:

#ifndef DEFINED_TYPEDEF_FOR_BasicColors #define DEFINED_TYPEDEF_FOR_BasicColors

typedef enum { BasicColors_Red = 0, /* Default value */ BasicColors_Yellow = 1, BasicColors_Blue = 2, } BasicColors;

#endif

The enumeration class name BasicColors appears as a prefix for each of the enumerated names.

Configure Enumerated DataTypes for Tunability in Generated Code

Since R2025a

When you import an enumerated data type definition defined in a header file that is external to the MATLAB environment, you can control whether the enumeration values are tunable in generated code. Tunable enumerated values enable you to share data type definitions,such as definitions that are provided in a master data dictionary, between applications. As needed, you can change, add, and reorder the enumerated values in generated code to align with requirements of each application.

By default, enumerated values in generated code are not tunable. To enable enumerated type tunability, include methods getHeaderFile,getDataScope, and isTunableInCode in themethods(Static) section of the enumeration class.

This example methods(Static) section for an enumeration class specifies that the generated code import the type definition fromimported_enum_type.h and enables tunability of the imported enumerated type values in generated code. To disable tunability, for methodisTunableInCode, specify the return valuefalse.

classdef BasicColors < Simulink.IntEnumType enumeration Red(0) Yellow(1) Blue(2) end methods (Static = true) function retVal = getDataScope() retVal = "Imported"; end
function retVal = getHeaderFile() retVal = "imported_enum_type.h"; end function retVal = isTunableInCode() retVal = true; end end end

The numeric value associated with each enumeration defined for a tunable enumerated type must be unique. For example, this enumerated class is invalid because enumerationsYellow and Blue are associated with the numeric value 1.

classdef BasicColors < Simulink.IntEnumType enumeration Red(0) Yellow(1) Blue(1) end methods (Static = true) function retVal = getDataScope() retVal = "Imported"; end
function retVal = getHeaderFile() retVal = "imported_enum_type.h"; end function retVal = isTunableInCode() retVal = true; end end end

Control Use of Duplicate Enumeration Member Names

When you import the enumeration data from a header file, you can control the use of duplicate enumeration member names during code generation. Duplicate enumeration member names improve the readability of the code. Use the model configuration parameter Duplicate enumeration member names to allow duplicate enumeration member names in different enumeration types during code generation or to generate an error or a warning message. You can use duplicate enumeration member names only if two enumerations have the same StorageType and have these specifications:

For example:

typedef int32_T enum { Red = 0, Yellow = 1, Blue = 2, }A;

typedef int32_T enum { Black = 0, Yellow = 1, White = 2, }B;

You can have a Yellow enumeration member in enumeration A and B without prefixing the member name with a class name to improve the readability of your code.

Control Enumerated Type Implementation in Generated Code

Suppose that you define an enumerated type BasicColors. You can specify that the generated code implement the type definition by using:

Implement Enumerated Type by Using enum Block

To implement the type definition by using an enum block:

When you generate code, the type definition appears in an enum block.

#ifndef DEFINED_TYPEDEF_FOR_BasicColors #define DEFINED_TYPEDEF_FOR_BasicColors

typedef enum { Red = 0, /* Default value */ Yellow, Blue, } BasicColors;

#endif

If you define the enumerated type inside a MATLAB namespace, by default, the code generator generates the enumeration in a namespace for C++ code generation. For C code generation, the code generator prefixes the enumeration with the MATLAB namespace. To disable the generation of C++ namespaces and C prefixes in the generated code, clear the model configuration parameter Preserve MATLAB namespaces in generated code.

This table displays the generated code for enumerated type Colors in the MATLAB namespace MyColors with Preserve MATLAB namespace in generated code selected and cleared.

Language Selected Cleared
C typedef enum { black, white, } MyColors_Colors; typedef enum { black, white } Colors;
C++ namespace MyColors { enum class Colors : int32_t { black, white }; } enum class Colors : int32_t { black, white };

Implement Enumerated Type Using a Specific Integer Type

To implement the type definition using a typedef statement and#define macros:

When you generate code, the type definition appears as a typedef statement and a series of #define macros.

#ifndef DEFINED_TYPEDEF_FOR_BasicColors #define DEFINED_TYPEDEF_FOR_BasicColors

typedef int8_T BasicColors;

#define Red ((BasicColors)0) /* Default value */ #define Yellow ((BasicColors)1) #define Blue ((BasicColors)2)

#endif

By default, the generated file_`model`__types.h contains enumerated type definitions.

Type Casting for Enumerations

Safe Casting

The Data Type Conversion block accepts a signal of integer type. The block converts the input to one of the underlying values of an enumerated type.

If the input value does not match an underlying value of an enumerated type value, Simulink inserts a safe cast to replace the input value with the enumerated type default value.

Enable and Disable Safe Casting

You can enable or disable safe casting for enumerations during code generation for a Data Type Conversion block or aStateflow block.

To control safe casting, enable or disable theSaturate on integer overflow block parameter. The parameter works as follows:

Safe Cast Function in Generated Code

This example shows how the safe cast functionint32_T ET08_safe_cast_to_BasicColors for the enumerationBasicColors appears in generated code when generated for 32-bit hardware.

static int32_T ET08_safe_cast_to_BasicColors(int32_T input) { int32_T output; /* Initialize output value to default value for BasicColors (Red) / output = 0; if ((input >= 0) && (input <= 2)) { / Set output value to input value if it is a member of BasicColors */ output = input; } return output; }

Through this function, the enumerated type’s default value is used if the input value does not match one of underlying values of the enumerated type’s values.

If the block’s Saturate on integer overflow parameter is disabled, this function does not appear in generated code.

Enumerated Type Limitations

See Also

enumeration | Simulink.defineIntEnumType | Simulink.data.getEnumTypeInfo | Simulink.data.dictionary.EnumTypeDefinition | Simulink.importExternalCTypes

Topics