General Code Generation Workflow

The general code generation workflow for the Statistics and Machine Learning Toolbox™ functions that are not the object functions of machine learning models is the same as the workflow described inMATLAB®Coder™。For details, seeGet Started with MATLAB Coder(MATLAB Coder). To learn how to generate code for the object functions of machine learning models, seeIntroduction to Code Generation

This example briefly explains the general code generation workflow as summarized in this flow chart:

Define Entry-Point Function

Anentry-pointfunction, also known as thetop-levelorprimaryfunction, is a function you define for code generation. Because you cannot call any function at the top level usingcodegen, you must define an entry-point function that calls code-generation-enabled functions, and generate C/C++ code for the entry-point function by usingcodegen。All functions within the entry-point function must support code generation.

Add the%#codegencompiler directive (or pragma) to the entry-point function after the function signature to indicate that you intend to generate code for the MATLAB algorithm. Adding this directive instructs the MATLAB Code Analyzer to help you diagnose and fix violations that would cause errors during code generation. SeeCheck Code with the Code Analyzer(MATLAB Coder).

For example, to generate code that estimates the interquartile range of a data set usingiqr, define this function.

functionr = iqrCodeGen(x)%#codegen%IQRCODEGEN Estimate interquartile range% iqrCodeGen returns the interquartile range of the data x,% a single- or double-precision vector.r = iqr(x);end
You can allow for optional input arguments by specifyingvararginas an input argument. For details, seeCode Generation for Variable Length Argument Lists(MATLAB Coder) andSpecify Variable-Size Arguments for Code Generation

Generate Code

Set Up Compiler

To generate C/C++ code, you must have access to a compiler that is configured properly.MATLAB Coderlocates and uses a supported, installed compiler. To view and change the default C compiler, enter:

mex-setup
For more details, seeChange Default Compiler(MATLAB).

Generate Code Usingcodegen

After setting up your compiler, generate code for the entry-point function by usingcodegenor theMATLAB Coderapp. To learn how to generate code using theMATLAB Coderapp, seeGenerate MEX Functions by Using the MATLAB Coder App(MATLAB Coder).

To generate code at the command line, usecodegen。因为C和c++静态类型语言, you must determine the properties of all variables in the entry-point function at compile time. Specify the data types and sizes of all inputs of the entry-point function when you callcodegenby using the-argsoption.

  • To specify the data type and exact input array size, pass a MATLAB expression that represents the set of values with a certain data type and array size. For example, to specify that the generated code fromiqrCodeGen.mmust accept a double-precision numeric column vector with 100 elements, enter:

    testX = randn(100,1); codegeniqrCodeGen-args{testX}-report

    The-reportflag generates a code generation report. SeeCode Generation Reports(MATLAB Coder).

  • To specify that at least one of the dimensions can have any length, use the-argsoption withcoder.typeofas follows.

    -args {coder.typeof(example_value,size_vector,variable_dims)}
    The values ofexample_value,size_vector, andvariable_dimsspecify the properties of the input array that the generated code can accept.

    • An input array has the same data type as the example values inexample_value

    • size_vectoris the array size of an input array if the correspondingvariable_dimsvalue isfalse

    • size_vectoris the upper bound of the array size if the correspondingvariable_dimsvalue istrue

    • variable_dimsspecifies whether each dimension of the array has a variable size or a fixed size. A value oftrue(logical 1) means that the corresponding dimension has a variable size; a value offalse(logical 0) means that the corresponding dimension has a fixed size.

    Specifying a variable-size input is convenient when you have data with an unknown number of observations at compile time. For example, to specify that the generated code fromiqrCodeGen.mcan accept a double-precision numeric column vector of any length, enter:

    testX = coder.typeof(0,[Inf,1],[1,0]); codegeniqrCodeGen-args{testX}-report

    0for theexample_valuevalue implies that the data type isdoublebecausedoubleis the default numeric data type of MATLAB.[Inf,1]for thesize_vectorvalue and[1,0]for thevariable_dimsvalue imply that the size of the first dimension is variable and unbounded, and the size of the second dimension is fixed to be 1.

  • To specify a character array, such as supported name-value pair arguments, specify the character array as a constant usingcoder.Constant。For example, suppose that'Name'is a valid name-value pair argument foriqrCodeGen.m, and the corresponding valuevalueis numeric. Then enter:

    codegeniqrCodeGen-args{testX,coder.Constant('Name'),value}-report

For more details, seeGenerate C Code at the Command Line(MATLAB Coder) andSpecify Properties of Entry-Point Function Inputs(MATLAB Coder).

Build Type

MATLAB Codercan generate code for these types:

  • MEX (MATLAB Executable) function

  • Standalone C/C++ code

  • Standalone C/C++ code compiled to a static library

  • 独立的C / c++代码编译为一个动态nked library

  • Standalone C/C++ code compiled to an executable

You can specify the build type using the-configoption ofcodegen。For more details on setting code generation options, seeConfigure Build Settings(MATLAB Coder).

By default,codegengenerates a MEX function. A MEX function is a C/C++ program that is executable from MATLAB. You can use a MEX function to accelerate MATLAB algorithms and to test the generated code for functionality and run-time issues. For details, seeMATLAB Algorithm Acceleration(MATLAB Coder) andWhy Test MEX Functions in MATLAB?(MATLAB Coder).

Code Generation Report

You can use the-reportflag to produce a code generation report. This report helps you debug code generation issues and view the generated C/C++ code. For details, seeCode Generation Reports(MATLAB Coder).

Verify Generated Code

Test a MEX function to verify that the generated code provides the same functionality as the original MATLAB code. To perform this test, run the MEX function using the same inputs that you used to run the original MATLAB code, and then compare the results. Running the MEX function in MATLAB before generating standalone code also enables you to detect and fix run-time errors that are much harder to diagnose in the generated standalone code. For more details, seeWhy Test MEX Functions in MATLAB?(MATLAB Coder).

Pass some data to verify whetheriqr,iqrCodeGen, andiqrCodeGen_mexreturn the same interquartile range.

testX = randn(100,1); r = iqr(testX); r_entrypoint = iqrCodeGen(testX); r_mex = iqrCodeGen_mex(testX);

Compare the outputs by usingisequal

isequal(r,r_entrypoint,r_mex)

isequalreturns logical 1 (true) if all the inputs are equal.

You can also verify the MEX function using a test file andcoder.runTest。For details, seeTesting Code Generated from MATLAB Code(MATLAB Coder).

See Also

Related Topics