MATLAB Classes Definition for Code Generation

To generate efficient standalone code for MATLAB® classes, you must use classes differently than when running your code in the MATLAB environment.

What’s DifferentMore Information
Restricted set of language features.Language Limitations
Restricted set of code generation features.Code Generation Features Not Compatible with Classes
Definition of class properties.Defining Class Properties for Code Generation
Use of handle classes.

Generate Code for MATLAB Handle Classes and System Objects

Code Generation for Handle Class Destructors

Handle Object Limitations for Code Generation

Calls to base class constructor.Calls to Base Class Constructor
Global variables containing MATLAB handle objects are not supported for code generation.N/A
Inheritance from built-in MATLAB classes is not supported.Inheritance from Built-In MATLAB Classes Not Supported

Language Limitations

Although code generation support is provided for common features of classes such as properties and methods, there are a number of advanced features which are not supported, such as:

  • Events

  • Listeners

  • Arrays of objects

  • Recursive data structures

    • Linked lists

    • Trees

    • Graphs

  • Nested functions in constructors

  • Overloadable operators subsref, subsassign, and subsindex

    In MATLAB, classes can define their own versions of the subsref, subsassign, and subsindex methods. Code generation does not support classes that have their own definitions of these methods.

  • The empty method

    In MATLAB, classes have a built-in static method, empty, which creates an empty array of the class. Code generation does not support this method.

  • The following MATLAB handle class methods:

    • addlistener

    • eq

    • findobj

    • findpro

  • The AbortSet property attribute

Code Generation Features Not Compatible with Classes

  • You can generate code for entry-point MATLAB functions that use classes, but you cannot generate code directly for a MATLAB class.

    For example, if ClassNameA is a class definition, you cannot generate code by executing:

    codegen ClassNameA

  • A handle class object cannot be an entry-point function input or output.

  • A value class object can be an entry-point function input or output. However, if a value class object contains a handle class object, then the value class object cannot be an entry-point function input or output. A handle class object cannot be an entry-point function input or output.

  • Code generation does not support global variables that are handle classes.

  • Code generation does not support assigning an object of a value class into a nontunable property. For example, obj.prop=v; is invalid when prop is a nontunable property and v is an object based on a value class.

  • You cannot use coder.extrinsic to declare a class or method as extrinsic.

  • You cannot pass a MATLAB class to coder.ceval. You can pass class properties to coder.ceval.

  • If a property has a get method, a set method, or validators, or is a System object™ property with certain attributes, then you cannot pass the property by reference to an external function. See Passing By Reference Not Supported for Some Properties.

  • If an object has duplicate property names and the code generator tries to constant-fold the object, code generation can fail. The code generator constant-folds an object when it is used with coder.Constant or coder.const, or when it is an input to or output from a constant-folded extrinsic function.

    Duplicate property names occur in an object of a subclass in these situations:

    • The subclass has a property with the same name as a property of the superclass.

    • The subclass derives from multiple superclasses that use the same name for a property.

    For information about when MATLAB allows duplicate property names, see Subclassing Multiple Classes.

Defining Class Properties for Code Generation

For code generation, you must define class properties differently than you do when running your code in the MATLAB environment:

  • MEX functions report errors that result from property validation. Standalone C/C++ code reports these errors only if you enable run-time error reporting. See Run-Time Error Detection and Reporting in Standalone C/C++ Code. Before you generate standalone C/C++ code, it is a best practice to test property validation by running a MEX function over the full range of input values.

  • After defining a property, do not assign it an incompatible type. Do not use a property before attempting to grow it.

    When you define class properties for code generation, consider the same factors that you take into account when defining variables. In the MATLAB language, variables can change their class, size, or complexity dynamically at run time so you can use the same variable to hold a value of varying class, size, or complexity. C and C++ use static typing. Before using variables, to determine their type, the code generator requires a complete assignment to each variable. Similarly, before using properties, you must explicitly define their class, size, and complexity.

  • Initial values:

    • If the property does not have an explicit initial value, the code generator assumes that it is undefined at the beginning of the constructor. The code generator does not assign an empty matrix as the default.

    • If the property does not have an initial value and the code generator cannot determine that the property is assigned prior to first use, the software generates a compilation error.

    • For System objects, if a nontunable property is a structure, you must completely assign the structure. You cannot do partial assignment using subscripting.

      For example, for a nontunable property, you can use the following assignment:

      mySystemObject.nonTunableProperty=struct('fieldA','a','fieldB','b');
      

      You cannot use the following partial assignments:

      mySystemObject.nonTunableProperty.fieldA = 'a';
      mySystemObject.nonTunableProperty.fieldB = 'b';

    • coder.varsize is not supported for class properties.

    • If the initial value of a property is an object, then the property must be constant. To make a property constant, declare the Constant attribute in the property block. For example:

      classdef MyClass 
          properties (Constant) 
              p1 = MyClass2; 
          end 
      end 

    • MATLAB computes class initial values at class loading time before code generation. If you use persistent variables in MATLAB class property initialization, the value of the persistent variable computed when the class loads belongs to MATLAB; it is not the value used at code generation time. If you use coder.target in MATLAB class property initialization, coder.target('MATLAB') returns true (1).

  • Variable-size properties:

    • Code generation supports upper-bounded and unbounded variable-size properties for both value and handle classes.

    • To generate unbounded variable-size class properties, enable dynamic memory allocation.

    • To make a variable-size class property, make two sequential assignments of a class property, one to a scalar and the next to an array.

      classdef varSizeProp1 < handle
          properties
              prop
              varProp
          end
      end
      
      function extFunc(n)
          obj = varSizeProp1;    
          % Assign a scalar value to the property.
          obj.prop = 1;
          obj.varProp = 1;
          % Assign an array to the same property to make it variable-sized.
          obj.prop = 1:98;    
          obj.varProp = 1:n;
      end

      In the preceding code, the first assignment to prop and varProp is scalar, and their second assignment is to an array with the same base type. The size of prop has an upper bound of 98, making it an upper-bounded, variable-size property.

      If n is unknown at compile time, obj.varProp is an unbounded variable-size property. If it is known, it is an upper-bounded, variable-size class property.

    • If the class property is initialized with a variable-size array, the property is variable-size.

      classdef varSizeProp2 
          properties
              prop
          end
          methods
              function obj = varSizeProp2(inVar)
                  % Assign incoming value to local variable
                  locVar = inVar;
                  
                  % Declare the local variable to be a variable-sized column             
                  % vector with no size limit
                  coder.varsize('locVar',[inf 1],[1 0]);
                  
                  % Assign value
                  obj.prop = locVar;
               end
          end
      end

      In the preceding code, inVar is passed to the class constructor and stored in locVar. locVar is modified to be variable-size by coder.varsize and assigned to the class property obj.prop, which makes the property variable-size.

      • If the input to the function call varSizeProp2 is variable-size, coder.varsize is not required.

        function z = constructCall(n)
            z = varSizeProp2(1:n);
        end
      • If the value is of n is unknown at compile-time and has no specified bounds, z.prop is an unbounded variable-size class property.

      • If the value is of n is unknown at compile-time and has specified bounds, z.prop is an upper-bounded variable-size class property.

  • If a property is constant and its value is an object, you cannot change the value of a property of that object. For example, suppose that:

    • obj is an object of myClass1.

    • myClass1 has a constant property p1 that is an object of myClass2.

    • myClass2 has a property p2.

    Code generation does not support the following code:

    obj.p1.p2 = 1;

Calls to Base Class Constructor

If a class constructor contains a call to the constructor of the base class, the call to the base class constructor must come before for, if, return, switch or while statements.

For example, if you define a class B based on class A:

classdef B < A
    methods
        function obj = B(varargin)
            if nargin == 0
                a = 1;
                b = 2;
            elseif nargin == 1
                a = varargin{1};
                b = 1;
            elseif nargin == 2
                a = varargin{1};
                b = varargin{2};
            end
            obj = obj@A(a,b);
        end    
        
    end
end

Because the class definition for B uses an if statement before calling the base class constructor for A, you cannot generate code for function callB:

function [y1,y2] = callB
x = B;
y1 = x.p1;
y2 = x.p2;
end

However, you can generate code for callB if you define class B as:

classdef B < A
    methods
        function obj = NewB(varargin)
            [a,b] = getaandb(varargin{:});
            obj = obj@A(a,b);
        end
        
    end
end

function [a,b] = getaandb(varargin)
if nargin == 0
    a = 1;
    b = 2;
elseif nargin == 1
    a = varargin{1};
    b = 1;
elseif nargin == 2
    a = varargin{1};
    b = varargin{2};
end
end

Inheritance from Built-In MATLAB Classes Not Supported

You cannot generate code for classes that inherit from built-in MATLAB classes. For example, you cannot generate code for the following class:

classdef myclass < double