Main Content

generateCode

Generate C/C++ code using coder configurer

Description

After training a machine learning model, create a coder configurer for the model by using learnerCoderConfigurer. Modify the properties of the configurer to specify code generation options. Then use generateCode to generate C/C++ code for the predict and update functions of the machine learning model. Generating C/C++ code requires MATLAB® Coder™.

This flow chart shows the code generation workflow using a coder configurer. Use generateCode for the highlighted step.

Two code generation workflows: the first after training a model, and the second after retraining the same model. First workflow, Step 1: Create a coder configurer. Step 2 (highlighted): Generate code. Step 3: Verify the generated code. Second workflow, Step 1: Check if the update is valid. If yes, go to Step 2; if no, go to the first step of the first workflow. Step 2: Update the model parameters in the generated code.

generateCode(configurer) generates a MEX (MATLAB Executable) function for the predict and update functions of a machine learning model by using configurer. The generated MEX function is named outputFileName, which is the file name stored in the OutputFileName property of configurer.

To generate a MEX function, generateCode first generates the following MATLAB files required to generate code and stores them in the current folder:

  • predict.m, update.m, and initialize.mpredict.m and update.m are the entry-point functions for the predict and update functions of the machine learning model, respectively, and these two functions call initialize.m.

  • A MAT-file that includes machine learning model information — generateCode uses the saveLearnerForCoder function to save machine learning model information in a MAT-file whose file name is stored in the OutputFileName property of a coder configurer. initialize.m loads the saved MAT-file by using the loadLearnerForCoder function.

After generating the necessary MATLAB files, generateCode creates the MEX function and the code for the MEX function in the codegen\mex\outputFileName folder and copies the MEX function to the current folder.

example

generateCode(configurer,cfg) generates C/C++ code using the build type specified by cfg.

example

generateCode(___,'OutputPath',outputPath) specifies the folder path for the output files in addition to any of the input arguments in previous syntaxes. generateCode generates the MATLAB files in the folder specified by outputPath and generates C/C++ code in the folder outputPath\codegen\type\outputFileName where type is the build type specified by cfg.

example

Examples

collapse all

Train a machine learning model, and then generate code for the predict and update functions of the model by using a coder configurer.

Load the carsmall data set and train a support vector machine (SVM) regression model.

load carsmall
X = [Horsepower,Weight];
Y = MPG;
Mdl = fitrsvm(X,Y);

Mdl is a RegressionSVM object, which is a linear SVM model. The predictor coefficients in a linear SVM model provide enough information to predict responses for new observations. Removing the support vectors reduces memory usage in the generated code. Remove the support vectors from the linear SVM model by using the discardSupportVectors function.

Mdl = discardSupportVectors(Mdl);

Create a coder configurer for the RegressionSVM model by using learnerCoderConfigurer. Specify the predictor data X. The learnerCoderConfigurer function uses the input X to configure the coder attributes of the predict function input.

configurer = learnerCoderConfigurer(Mdl,X)
Warning: Default response is removed to support learnerCoderConfigurer. The model will predict NaNs for observations with missing values.
configurer = 
  RegressionSVMCoderConfigurer with properties:

   Update Inputs:
              Beta: [1x1 LearnerCoderInput]
             Scale: [1x1 LearnerCoderInput]
              Bias: [1x1 LearnerCoderInput]

   Predict Inputs:
                 X: [1x1 LearnerCoderInput]

   Code Generation Parameters:
        NumOutputs: 1
    OutputFileName: 'RegressionSVMModel'


configurer is a RegressionSVMCoderConfigurer object, which is a coder configurer of a RegressionSVM object.

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.

Generate code for the predict and update functions of the SVM regression model (Mdl) with default settings.

generateCode(configurer)
generateCode creates these files in output folder:
'initialize.m', 'predict.m', 'update.m', 'RegressionSVMModel.mat'
Code generation successful.

The generateCode function completes these actions:

  • Generate the MATLAB files required to generate code, including the two entry-point functions predict.m and update.m for the predict and update functions of Mdl, respectively.

  • Create a MEX function named RegressionSVMModel for the two entry-point functions.

  • Create the code for the MEX function in the codegen\mex\RegressionSVMModel folder.

  • Copy the MEX function to the current folder.

Display the contents of the predict.m, update.m, and initialize.m files by using the type function.

type predict.m
function varargout = predict(X,varargin) %#codegen
% Autogenerated by MATLAB, 05-Sep-2024 19:47:50
[varargout{1:nargout}] = initialize('predict',X,varargin{:});
end
type update.m
function update(varargin) %#codegen
% Autogenerated by MATLAB, 05-Sep-2024 19:47:50
initialize('update',varargin{:});
end
type initialize.m
function [varargout] = initialize(command,varargin) %#codegen
% Autogenerated by MATLAB, 05-Sep-2024 19:47:50
coder.inline('always')
persistent model
if isempty(model)
    model = loadLearnerForCoder('RegressionSVMModel.mat');
end
switch(command)
    case 'update'
        % Update struct fields: Beta
        %                       Scale
        %                       Bias
        model = update(model,varargin{:});
    case 'predict'
        % Predict Inputs: X
        X = varargin{1};
        if nargin == 2
            [varargout{1:nargout}] = predict(model,X);
        else
            PVPairs = cell(1,nargin-2);
            for i = 1:nargin-2
                PVPairs{1,i} = varargin{i+1};
            end
            [varargout{1:nargout}] = predict(model,X,PVPairs{:});
        end
end
end

Train a machine learning model and generate code by using the coder configurer of the trained model. When generating code, specify the build type and other configuration options using a code generation configuration object.

Load the ionosphere data set.

load ionosphere

Train a binary support vector machine (SVM) classification model, using a Gaussian kernel function with an automatic kernel scale.

Mdl = fitcsvm(X,Y, ...
    'KernelFunction','gaussian','KernelScale','auto');

Mdl is a ClassificationSVM object.

Create a coder configurer for the ClassificationSVM model by using learnerCoderConfigurer. Specify the predictor data X. The learnerCoderConfigurer function uses the input X to configure the coder attributes of the predict function input.

configurer = learnerCoderConfigurer(Mdl,X);

configurer is a ClassificationSVMCoderConfigurer object, which is a coder configurer of a ClassificationSVM object.

Create a code generation configuration object by using coder.config (MATLAB Coder). Specify 'dll' to generate a dynamic library and specify the GenerateReport property as true to enable the code generation report.

cfg = coder.config('dll');
cfg.GenerateReport = true;

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.

Use generateCode and the configuration object cfg to generate code. Also, specify the output folder path.

generateCode(configurer,cfg,'OutputPath','testPath')
Specified folder does not exist. Folder has been created.
generateCode creates these files in output folder:
'initialize.m', 'predict.m', 'update.m', 'ClassificationSVMModel.mat'
Code generation successful: To view the report, open('codegen/dll/ClassificationSVMModel/html/report.mldatx')

generateCode creates the specified folder. The function also generates the MATLAB files required to generate code and stores them in the folder. Then generateCode generates C code in the testPath\codegen\dll\ClassificationSVMModel folder.

Train an error-correcting output codes (ECOC) model using SVM binary learners and create a coder configurer for the model. Use the properties of the coder configurer to specify coder attributes of the ECOC model parameters. Use the object function of the coder configurer to generate C code that predicts labels for new predictor data. Then retrain the model using different settings, and update parameters in the generated code without regenerating the code.

Train Model

Load Fisher's iris data set.

load fisheriris
X = meas;
Y = species;

Create an SVM binary learner template to use a Gaussian kernel function and to standardize predictor data.

t = templateSVM('KernelFunction','gaussian','Standardize',true);

Train a multiclass ECOC model using the template t.

Mdl = fitcecoc(X,Y,'Learners',t);

Mdl is a ClassificationECOC object.

Create Coder Configurer

Create a coder configurer for the ClassificationECOC model by using learnerCoderConfigurer. Specify the predictor data X. The learnerCoderConfigurer function uses the input X to configure the coder attributes of the predict function input. Also, set the number of outputs to 2 so that the generated code returns the first two outputs of the predict function, which are the predicted labels and negated average binary losses.

configurer = learnerCoderConfigurer(Mdl,X,'NumOutputs',2)
configurer = 
  ClassificationECOCCoderConfigurer with properties:

   Update Inputs:
    BinaryLearners: [1x1 ClassificationSVMCoderConfigurer]
             Prior: [1x1 LearnerCoderInput]
              Cost: [1x1 LearnerCoderInput]

   Predict Inputs:
                 X: [1x1 LearnerCoderInput]

   Code Generation Parameters:
        NumOutputs: 2
    OutputFileName: 'ClassificationECOCModel'


configurer is a ClassificationECOCCoderConfigurer object, which is a coder configurer of a ClassificationECOC object. The display shows the tunable input arguments of predict and update: X, BinaryLearners, Prior, and Cost.

Specify Coder Attributes of Parameters

Specify the coder attributes of predict arguments (predictor data and the name-value pair arguments 'Decoding' and 'BinaryLoss') and update arguments (support vectors of the SVM learners) so that you can use these arguments as the input arguments of predict and update in the generated code.

First, specify the coder attributes of X so that the generated code accepts any number of observations. Modify the SizeVector and VariableDimensions attributes. The SizeVector attribute specifies the upper bound of the predictor data size, and the VariableDimensions attribute specifies whether each dimension of the predictor data has a variable size or fixed size.

configurer.X.SizeVector = [Inf 4];
configurer.X.VariableDimensions = [true false];

The size of the first dimension is the number of observations. In this case, the code specifies that the upper bound of the size is Inf and the size is variable, meaning that X can have any number of observations. This specification is convenient if you do not know the number of observations when generating code.

The size of the second dimension is the number of predictor variables. This value must be fixed for a machine learning model. X contains 4 predictors, so the second value of the SizeVector attribute must be 4 and the second value of the VariableDimensions attribute must be false.

Next, modify the coder attributes of BinaryLoss and Decoding to use the 'BinaryLoss' and 'Decoding' name-value pair arguments in the generated code. Display the coder attributes of BinaryLoss.

configurer.BinaryLoss
ans = 
  EnumeratedInput with properties:

             Value: 'hinge'
    SelectedOption: 'Built-in'
    BuiltInOptions: {'hamming'  'linear'  'quadratic'  'exponential'  'binodeviance'  'hinge'  'logit'}
        IsConstant: 1
        Tunability: 0

To use a nondefault value in the generated code, you must specify the value before generating the code. Specify the Value attribute of BinaryLoss as 'exponential'.

configurer.BinaryLoss.Value = 'exponential';
configurer.BinaryLoss
ans = 
  EnumeratedInput with properties:

             Value: 'exponential'
    SelectedOption: 'Built-in'
    BuiltInOptions: {'hamming'  'linear'  'quadratic'  'exponential'  'binodeviance'  'hinge'  'logit'}
        IsConstant: 1
        Tunability: 1

If you modify attribute values when Tunability is false (logical 0), the software sets the Tunability to true (logical 1).

Display the coder attributes of Decoding.

configurer.Decoding
ans = 
  EnumeratedInput with properties:

             Value: 'lossweighted'
    SelectedOption: 'Built-in'
    BuiltInOptions: {'lossweighted'  'lossbased'}
        IsConstant: 1
        Tunability: 0

Specify the IsConstant attribute of Decoding as false so that you can use all available values in BuiltInOptions in the generated code.

configurer.Decoding.IsConstant = false;
configurer.Decoding
ans = 
  EnumeratedInput with properties:

             Value: [1x1 LearnerCoderInput]
    SelectedOption: 'NonConstant'
    BuiltInOptions: {'lossweighted'  'lossbased'}
        IsConstant: 0
        Tunability: 1

The software changes the Value attribute of Decoding to a LearnerCoderInput object so that you can use both 'lossweighted' and 'lossbased' as the value of 'Decoding'. Also, the software sets the SelectedOption to 'NonConstant' and the Tunability to true.

Finally, modify the coder attributes of SupportVectors in BinaryLearners. Display the coder attributes of SupportVectors.

configurer.BinaryLearners.SupportVectors
ans = 
  LearnerCoderInput with properties:

            SizeVector: [54 4]
    VariableDimensions: [1 0]
              DataType: 'double'
            Tunability: 1

The default value of VariableDimensions is [true false] because each learner has a different number of support vectors. If you retrain the ECOC model using new data or different settings, the number of support vectors in the SVM learners can vary. Therefore, increase the upper bound of the number of support vectors.

configurer.BinaryLearners.SupportVectors.SizeVector = [150 4];
SizeVector attribute for Alpha has been modified to satisfy configuration constraints.
SizeVector attribute for SupportVectorLabels has been modified to satisfy configuration constraints.

If you modify the coder attributes of SupportVectors, then the software modifies the coder attributes of Alpha and SupportVectorLabels to satisfy configuration constraints. If the modification of the coder attributes of one parameter requires subsequent changes to other dependent parameters to satisfy configuration constraints, then the software changes the coder attributes of the dependent parameters.

Display the coder configurer.

configurer
configurer = 
  ClassificationECOCCoderConfigurer with properties:

   Update Inputs:
    BinaryLearners: [1x1 ClassificationSVMCoderConfigurer]
             Prior: [1x1 LearnerCoderInput]
              Cost: [1x1 LearnerCoderInput]

   Predict Inputs:
                 X: [1x1 LearnerCoderInput]
        BinaryLoss: [1x1 EnumeratedInput]
          Decoding: [1x1 EnumeratedInput]

   Code Generation Parameters:
        NumOutputs: 2
    OutputFileName: 'ClassificationECOCModel'


The display now includes BinaryLoss and Decoding as well.

Generate Code

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.

Generate code for the predict and update functions of the ECOC classification model (Mdl).

generateCode(configurer)
generateCode creates these files in output folder:
'initialize.m', 'predict.m', 'update.m', 'ClassificationECOCModel.mat'
Code generation successful.

The generateCode function completes these actions:

  • Generate the MATLAB files required to generate code, including the two entry-point functions predict.m and update.m for the predict and update functions of Mdl, respectively.

  • Create a MEX function named ClassificationECOCModel for the two entry-point functions.

  • Create the code for the MEX function in the codegen\mex\ClassificationECOCModel folder.

  • Copy the MEX function to the current folder.

Verify Generated Code

Pass some predictor data to verify whether the predict function of Mdl and the predict function in the MEX function return the same labels. To call an entry-point function in a MEX function that has more than one entry point, specify the function name as the first input argument. Because you specified 'Decoding' as a tunable input argument by changing the IsConstant attribute before generating the code, you also need to specify it in the call to the MEX function, even though 'lossweighted' is the default value of 'Decoding'.

[label,NegLoss] = predict(Mdl,X,'BinaryLoss','exponential');
[label_mex,NegLoss_mex] = ClassificationECOCModel('predict',X,'BinaryLoss','exponential','Decoding','lossweighted');

Compare label to label_mex by using isequal.

isequal(label,label_mex)
ans = logical
   1

isequal returns logical 1 (true) if all the inputs are equal. The comparison confirms that the predict function of Mdl and the predict function in the MEX function return the same labels.

NegLoss_mex might include round-off differences compared to NegLoss. In this case, compare NegLoss_mex to NegLoss, allowing a small tolerance.

find(abs(NegLoss-NegLoss_mex) > 1e-8)
ans =

  0x1 empty double column vector

The comparison confirms that NegLoss and NegLoss_mex are equal within the tolerance 1e–8.

Retrain Model and Update Parameters in Generated Code

Retrain the model using a different setting. Specify 'KernelScale' as 'auto' so that the software selects an appropriate scale factor using a heuristic procedure.

t_new = templateSVM('KernelFunction','gaussian','Standardize',true,'KernelScale','auto');
retrainedMdl = fitcecoc(X,Y,'Learners',t_new);

Extract parameters to update by using validatedUpdateInputs. This function detects the modified model parameters in retrainedMdl and validates whether the modified parameter values satisfy the coder attributes of the parameters.

params = validatedUpdateInputs(configurer,retrainedMdl);

Update parameters in the generated code.

ClassificationECOCModel('update',params)

Verify Generated Code

Compare the outputs from the predict function of retrainedMdl to the outputs from the predict function in the updated MEX function.

[label,NegLoss] = predict(retrainedMdl,X,'BinaryLoss','exponential','Decoding','lossbased');
[label_mex,NegLoss_mex] = ClassificationECOCModel('predict',X,'BinaryLoss','exponential','Decoding','lossbased');
isequal(label,label_mex)
ans = logical
   1

find(abs(NegLoss-NegLoss_mex) > 1e-8)
ans =

  0x1 empty double column vector

The comparison confirms that label and label_mex are equal, and NegLoss and NegLoss_mex are equal within the tolerance.

Input Arguments

collapse all

Coder configurer of a machine learning model, specified as a coder configurer object created by using learnerCoderConfigurer.

ModelCoder Configurer Object
Binary decision tree for multiclass classificationClassificationTreeCoderConfigurer
SVM for one-class and binary classificationClassificationSVMCoderConfigurer
Linear model for binary classificationClassificationLinearCoderConfigurer
Multiclass model for SVMs and linear modelsClassificationECOCCoderConfigurer
Binary decision tree for regressionRegressionTreeCoderConfigurer
Support vector machine (SVM) regressionRegressionSVMCoderConfigurer
Linear regressionRegressionLinearCoderConfigurer

Build type, specified as 'mex', 'dll', 'lib', or a code generation configuration object created by coder.config (MATLAB Coder).

generateCode generates C/C++ code using one of the following build types.

  • 'mex' — Generates a MEX function that has a platform-dependent extension. A MEX function is a C/C++ program that is executable from the Command Window. Before generating a C/C++ library for deployment, generate a MEX function to verify that the generated code provides the correct functionality.

  • 'dll' — Generate a dynamic C/C++ library.

  • 'lib' — Generate a static C/C++ library.

  • Code generation configuration object created by coder.config (MATLAB Coder) — Generate C/C++ code using the code generation configuration object to customize code generation options. You can specify the build type and other configuration options using the object. For example, modify the GenerateReport parameter to enable the code generation report, and modify the TargetLang parameter to generate C++ code. The default value of the TargetLang parameter is 'C', generating C code.

    cfg = coder.config('mex');
    cfg.GenerateReport = true;
    cfg.TargetLang = 'C++';
    For details, see the -config option of codegen (MATLAB Coder), coder.config (MATLAB Coder), and Configure Code Generation and Build Settings (MATLAB Coder).

generateCode generates C/C++ code in the folder outputPath\codegen\type\outputFileName, where type is the build type specified by the cfg argument and outputFileName is the file name stored in the OutputFileName property of configurer.

Folder path for the output files of generateCode, specified as a character vector or string array.

The specified folder path can be an absolute path or a relative path to the current folder path.

  • The path must not contain spaces because they can lead to code generation failures in certain operating system configurations.

  • The path also cannot contain non-7-bit ASCII characters, such as Japanese characters.

If the specified folder does not exist, then generateCode creates the folder.

generateCode searches the specified folder for the four MATLAB files: predict.m, update.m, initialize.m, and a MAT-file that includes machine learning model information. If the four files do not exist in the folder, then generateCode generates the files. Otherwise, generateCode does not generate any MATLAB files.

generateCode generates C/C++ code in the folder outputPath\codegen\type\outputFileName, where type is the build type specified by the cfg argument and outputFileName is the file name stored in the OutputFileName property of configurer.

Example: 'C:\myfiles'

Data Types: char | string

Limitations

Alternative Functionality

  • If you want to modify the MATLAB files (predict.m, update.m, and initialize.m) according to your code generation workflow, then use generateFiles to generate these files and use codegen (MATLAB Coder) to generate code.

Version History

Introduced in R2018b