Main Content

Create Variant Controls Using MATLAB® Enumeration Class

Each variant choice in a Simulink® model is associated with a conditional expression called a variant control. The variant control which evaluates to true determines the active variant choice in the model. This example shows how to create variant controls in your model using a MATLAB® enumeration in the variant condition expressions. In code generation, enumerated types improve readability because condition values are represented as meaningful names instead of literal values.

Explore the Model

Open the model slexVariantSetupUsingIntEnums. It contains two variant choices, Linear controller and Nonlinear controller. Variant Sink and Variant Source blocks are used to implement the variant regions.

Specify the Enumeration Class in a MATLAB® File

You can create an enumeration class by adding an enumeration block to a class definition and saving it in a MATLAB file. In this example, the enumeration ControllerChoice (saved in ControllerChoice.m) derives from the built-in numeric type int32. It defines two enumeration members, Linear and Nonlinear.

classdef ControllerChoice < int32
        Linear (0),
        Nonlinear (1),
    %All the methods below can be optionally used to configure
    %the enumeration in the generated code
    methods (Static = true)
        %% Description of the enumeration
        function retVal = getDescription()
            retVal = 'Controller...';
        %% Default value of the enumeration
        function retVal = getDefaultValue()
            retVal = ControllerChoice.Linear;
        %% Specify whether the generated code imports/exports the definition
        %% of the enum used in the variant control expression
        function retVal = getDataScope()
            retVal = 'Exported';
        %% Get the header file to import from/export to the definition of the
        %% enumeration in the generated code
        function retVal = getHeaderFile()
            retVal = 'Controller.h';

Create a Variant Control Variable

This example uses the MATLAB variable V as the variant control variable to store the variant choice that is currently active.

In the MATLAB Command Window, type:

V = ControllerChoice.Linear;

Build the Variant Condition Expression

You can set the variant controls from the Variant Manager. To open the Variant Manager, right-click the variant badge on the Variant Sink or Variant Source block and select Open in Variant Manager .

You can see how the enumeration members and the control variable is used to create the condition expressions V == ControllerChoice.Linear and V == ControllerChoice.Nonlinear. All supported Simulink enumerations can be used to build the condition expression. For information on enumerations in Simulink, see Simulink Enumerations.

See Also