Note: This page has been translated by MathWorks. Click here to see

To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

This example shows how to generate code for the prediction of classification and regression model objects at the command line. You can also generate code using the MATLAB® Coder™ app. See Code Generation for Prediction of Machine Learning Model Using MATLAB Coder App for details.

Certain classification and regression model objects have a `predict`

or `random`

function that supports code generation. For a list of the model objects and object functions that support code generation, see Code Generation Support, Usage Notes, and Limitations. Prediction using these object functions requires a trained classification or regression model object, but the `-args`

option of `codegen`

does not accept these objects. Work around this limitation by using `saveCompactModel`

and `loadCompactModel`

as described in this example.

This flow chart shows the code generation workflow for the object functions of classification and regression model objects.

After you train a model, save the trained model by using `saveCompactModel`

. Define an entry-point function that loads the saved model by using `loadCompactModel`

and calls the object function. Then generate code for the entry-point function by using `codegen`

, and verify the generated code.

Train a classification model object equipped with a code-generation-enabled `predict`

function. In this case, train a support vector machine (SVM) classification model.

load fisheriris inds = ~strcmp(species,'setosa'); X = meas(inds,3:4); Y = species(inds); Mdl = fitcsvm(X,Y);

This step can include data preprocessing, feature selection, and optimizing the model using cross-validation, for example.

`saveCompactModel`

Save the classification model to the file `SVMModel.mat`

by using `saveCompactModel`

.

`saveCompactModel(Mdl,'SVMModel');`

`saveCompactModel`

makes the full classification model `Mdl`

compact, and then saves it to the MATLAB binary file `SVMModel.mat`

as a structure array in the current folder.

An *entry-point* function, also known as the *top-level* or *primary* function, is a function you define for code generation. Because you cannot call any function at the top level using `codegen`

, you must define an entry-point function that calls code-generation-enabled functions, and generate C/C++ code for the entry-point function by using `codegen`

. All functions within the entry-point function must support code generation.

Define an entry-point function that returns predicted labels for input predictor data. Within the function, load the trained classification model by using `loadCompactModel`

, and then pass the loaded model to `predict`

. In this case, define the `predictLabelsSVM`

function, which predicts labels using the SVM model `Mdl`

.

type predictLabelsSVM.m % Display contents of predictLabelsSVM.m file

function label = predictLabelsSVM(x) %#codegen %PREDICTLABELSSVM Label new observations using trained SVM model Mdl % predictLabelsSVM predicts the vector of labels label using % the saved SVM model Mdl and the predictor data x. Mdl = loadCompactModel('SVMModel'); label = predict(Mdl,x); end

Add the `%#codegen`

compiler 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 result in errors during code generation. See Check Code with the Code Analyzer (MATLAB Coder).

**Note:** If you click the button located in the upper-right section of this page and open this example in MATLAB®, then MATLAB® opens the example folder. This folder includes the entry-point function file.

**Set Up Compiler**

To generate C/C++ code, you must have access to a C/C++ compiler that is configured properly. MATLAB Coder locates and uses a supported, installed compiler. You can use `mex`

`-setup`

to view and change the default compiler. For more details, see Change Default Compiler (MATLAB).

**Generate Code Using **`codegen`

Generate code for the entry-point function using `codegen`

. Because C and C++ are statically typed languages, 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 call `codegen`

by using the `-args`

option.

In this case, pass `X`

as a value of the `-args`

option to specify that the generated code must accept an input that has the same data type and array size as the training data `X`

.

codegen predictLabelsSVM -args {X}

If the number of observations is unknown at compile time, you can also specify the input as variable-size by using `coder.typeof`

. For details, see Specify Variable-Size Arguments for Code Generation and Specify Properties of Entry-Point Function Inputs (MATLAB Coder)

**Build Type**

MATLAB Coder can generate code for the following build types:

MEX (MATLAB Executable) function

Standalone C/C++ code

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

Standalone C/C++ code compiled to a dynamically linked library

Standalone C/C++ code compiled to an executable

You can specify the build type using the `-config`

option of `codegen`

. For more details on setting code generation options, see the `-config`

option of `codegen`

and Configure Build Settings (MATLAB Coder).

By default, codegen generates 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, see MATLAB Algorithm Acceleration (MATLAB Coder) and Why Test MEX Functions in MATLAB? (MATLAB Coder).

**Code Generation Report**

You can use the `-report`

flag to produce a code generation report. This report helps you debug code generation issues and view the generated C/C++ code. For details, see Code Generation Reports (MATLAB Coder).

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, see Why Test MEX Functions in MATLAB? (MATLAB Coder).

Pass some predictor data to verify whether `predict`

, `predictLabelsSVM`

, and the MEX function return the same labels.

labels1 = predict(Mdl,X); labels2 = predictLabelsSVM(X); labels3 = predictLabelsSVM_mex(X);

Compare the predicted labels by using `isequal`

.

verifyMEX = isequal(labels1,labels2,labels3)

`verifyMEX = `*logical*
1

`isequal`

returns logical 1 (`true`

), which means all the inputs are equal. The comparison confirms that the `predict`

function, `predictLabelsSVM`

function, and MEX function return the same labels.

`codegen`

| `learnerCoderConfigurer`

| `loadCompactModel`

| `saveCompactModel`