Generate Code for MATLAB Handle Classes and System Objects - MATLAB & Simulink (original) (raw)

Main Content

This example shows how to generate code for a user-defined System objectâ„¢ and then view the generated code in the code generation report.

  1. In a writable folder, create a System object, AddOne, which subclasses from matlab.System. Save the code as AddOne.m.
    classdef AddOne < matlab.System
    % ADDONE Compute an output value that increments the input by one
    methods (Access=protected)
    % stepImpl method is called by the step method
    function y = stepImpl(~,x)
    y = x+1;
    end
    end
    end
  2. Write a function that uses this System object.
    function y = testAddOne(x)
    %#codegen
    p = AddOne();
    y = p.step(x);
    end
  3. Generate a MEX function for this code.
    codegen -report testAddOne -args {0}
    The -report option instructs codegen to generate a code generation report, even if no errors or warnings occur. The -args option specifies that thetestAddOne function takes one scalar double input.
  4. Click the View report link.
  5. In the MATLAB Source pane, click testAddOne. To see information about the variables in testAddOne, click theVariables tab.
    This shows the MATLAB function testAddOne in the report. The cursor points to the variable p and the properties display.
  6. To view the class definition for addOne, in the MATLAB Source pane, click AddOne.
    This image shows the class definition for addOne in the report.