Documentation

Use Enumerated Data in金宝appModels

Enumerated datais data that is restricted to a finite set of values. Anenumerated data typeis a MATLAB®class that defines a set ofenumerated values. Each enumerated value consists of anenumerated nameand anunderlying integerwhich the software uses internally and in generated code.

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

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

Define金宝appEnumerations

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

  • Define an enumeration class using aclassdefblock in a MATLAB file.

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

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

Workflow to Define a金宝appEnumeration Class

Create金宝appEnumeration Class

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

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

  • Add anenumerationblock 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 classSimulink.IntEnumType. The enumeration is integer-based becauseIntEnumTypeis derived fromint32.

Theenumeration部分指定三个枚举值。

Enumerated Value Enumerated Name Underlying Integer
Red(0) Red 0
Yellow(1) Yellow 1
Blue(2) Blue 2

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 theenumerationsection 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 anyint32value. Use the MATLAB functionsintminandintmaxto 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. SeeConfigure a System Target File(Simulink Coder) for more information.

For more information on superclasses, seeConvert to Superclass Value(MATLAB). For information on how enumeration classes are handled when there is more than one name for an underlying value, seeHow to Alias Enumeration Names(MATLAB).

Customize金宝appEnumeration

About金宝appEnumeration 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 Method Purpose Default Value Without Implementing Method Custom Return Value Usage Context
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 (seeInstantiate Enumerations) Simulation and code generation
getDescription Specifies a description of the enumeration class. '' A character vector containing the description of the type Code generation
getHeaderFile Specifies the name of a header file. The methodgetDataScopedetermines the significance of the file. '' A character vector containing the name of the header file that defines the enumerated type Code generation
getDataScope Specifies whether generated code exports or imports the definition of the enumerated data type. Use the methodgetHeaderFileto specify the generated or included header file that defines the type. 'Auto' One of:'Auto','Exported', or'Imported' Code generation
addClassNameToEnumNames Specifies whether to prefix the class name in generated code. false trueorfalse Code generation

For more examples of these methods as they apply to code generation, seeCustomize 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 inType 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 owngetDefaultValuemethod to themethodssection. The following code shows a shell for thegetDefaultValuemethod:

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 forThisClass.EnumNamethat specifies the desired default.

  • ThisClassmust be the name of the class within which the method exists.

  • EnumNamemust 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 asBasicColors.Blue. If this method does not appear, the default value would beBasicColors.Red, because that is the first value listed in the enumerated class definition.

The seemingly redundant specification ofThisClass在相同的类是表示“必需的”的定义ary becausegetDefaultValuereturns 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. SeeInstantiate Enumerationsfor more information.

Save Enumeration in aMATLABFile

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 enumerationBasicColorsmust reside in a file namedBasicColors.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, typeaddpathpathnameat the MATLAB command prompt. For more information, seeWhat Is the MATLAB Search Path?(MATLAB),addpath, andsavepath.

  • 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 theclearcommand.

  • 通过关闭所有模型th删除过时的实例at 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 usingSimulink.defineIntEnumType,你可以定义类,使用相同的函数tion, even if instances exist. However, you cannot changeStorageTypefor the class while instances exist.

For more information about applying enumeration changes, seeAutomatic Updates for Modified Classes(MATLAB).

Import Enumerations Defined Externally toMATLAB

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

    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 aMATLAB Functionblock in your model uses the enumerated type, configure the model configuration parameters to include (#include) the type definition from your external header file. SeeControl 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 functionSimulink.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, seeEnumerations in Data Dictionary.

Simulate with Enumerations

Consider the following enumeration class definition —BasicColorswith enumerated valuesRed,Yellow, andBlue, withBlueas 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 inEnumerated Data(Stateflow). The following Simulink model uses the enumeration defined above:

The output of the model looks like this:

TheData Type ConversionblockOrigToIntspecifies anOutput data typeofint32andInteger rounding mode:Floor, so the block converts theSine Waveblock output, which appears in the top graph of theScopedisplay, to a cycle of integers:1,2,1,0,1,2,1. TheData Type ConversionblockIntToColoruses these values to select colors from the enumerated typeBasicColorsby referencing their underlying integers.

The result is a cycle of colors:Yellow,Blue,Yellow,Red,Yellow,Blue,Yellow, as shown in the middle graph. TheEnumerated ConstantblockEnumConstoutputsYellow, which appears in the second graph as a straight line. TheRelational Operatorblock compares the constantYellowto each value in the cycle of colors. It outputs1(true) whenYellowis less than the current color, and0(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,notthe 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. SeeSpecify Enumerations as Data TypesandEnumerated Values in Computationfor 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 ? orEnum: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, butEnum:is preferred because it is more self-explanatory in the context of a graphical user interface.

Depending on the context, typeEnum:followed by the name of an enumeration, or selectEnum: from a menu (for example, for theOutput data typeblock parameter) , and replace.

To use the Data Type Assistant, set theModetoEnumerated, then enter the name of the enumeration. For example, in the previous model, theData Type ConversionblockIntToColor, which outputs a signal of typeBasicColors, 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. SeeEnumerated Values in Computationfor more information.

Get Information About Enumerated Data Types

The functionsenumerationandSimulink.data.getEnumTypeInforeturn information about enumerated data types.

Get Information About Enumeration Members

Use the functionenumerationto:

  • 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 theCase conditionsparameter of the Switch Case block

Get Information About Enumerated Class

Use the functionSimulink.data.getEnumTypeInfoto 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 inScopeandFloating Scopeblocks.

Block... Affect on Value Display...
Scope When 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 Scope When displaying signals that are of the same enumeration, names appear on the Y axis as they would for aScopeblock. If theFloating Scopeblock 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 inSpecify Enumerations as Data Types. When this occurs, the value on an axis ofScopeblock output or inDisplayblock output always is the first value listed in the enumerated class definition that has the shared underlying integer. For example:

Although theEnumerated Constantblock outputsTrue, bothOnandTruehave the same underlying integer, andOnis defined first in the class definitionenumerationsection. Therefore, theDisplayblock showsOn. Similarly, aScopeaxis would show onlyOn, neverTrue, no matter which of the two values is input to theScopeblock.

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 inMATLAB

To instantiate an enumeration in MATLAB, enterClassName.EnumNamein the MATLAB Command Window. The instance is created in the base workspace. For example, ifBasicColorsis defined as inCreate Simulink Enumeration Class, you can type:

bcy = BasicColors.Yellow bcy = Yellow

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

bcy = BasicColors.

MATLAB displays the elements and methods ofBasicColorsin alphabetical order:

Double-click an element or method to insert it at the position where you pressed. SeeCode Suggestions and Completions(MATLAB) for more information.

Casting Enumerations inMATLAB

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金宝app(orStateflow)

To instantiate an enumeration in a Simulink model, you can enterClassName.EnumNameas a value in a dialog box. For example, consider the following model:

TheEnumerated ConstantblockEnumConst, which outputs the enumerated valueYellow, defines that value as follows:

您可以输入任何有效的MATLAB表达式,伊娃luates to an enumerated value, including arrays and workspace variables. For example, you could enterBasicColors(1), or if you had previously executedbcy = BasicColors.Yellowin the MATLAB Command Window, you could enterbcy. As another example, you could enter an array, such as[BasicColors.Red, BasicColors.Yellow, BasicColors.Blue].

You can use aConstantblock to output enumerated values. However, that block displays parameters that do not apply to enumerated types, such asOutput MinimumandOutput Maximum.

If you create aSimulink.Parameterobject as an enumeration, you must specify theValueparameter as an enumeration member and theData typewith theEnum:or ? prefix, as explained inSpecify Enumerations as Data Types.

Youcannotspecify the integer value of an enumeration member for theValueparameter. SeeEnumerated Values in Computationfor more information. Thus, the following fails even though the integer value forBasicColors.Yellowis1.

The same syntax and considerations apply in Stateflow. SeeEnumerated 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 MATLABint32class. 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.

您可以使用一个转换数据类型转换块t 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. SeeCasting Enumerated Signalsfor 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 inSimulate with Enumerationsneeded two Data Conversion blocks to convert a sine wave to enumerated values.

The first block castsdoubletoint32, and the second block castsint32toBasicColors. 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 anEnumerated Constantblock specifies aValueof2and anOutput data typeofEnum: BasicColors:

An error occurs because the specifications implicitly cast adoublevalue 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 aConstantblock specifies aConstant valueofBasicColors.Blueand anOutput data typeofint32.

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

See Also

||

Related Topics