Main Content

Replace Code Generated from MATLAB Code

This example shows how to replace generated code using a code replacement library. Code replacement is a technique for changing the code that the code generator produces for functions and operators to meet application code requirements.

Prepare for Code Replacement

  1. Make sure that you have installed required software. Required software is:

    • MATLAB®

    • MATLAB Coder™

    • C compiler

    Some code replacement libraries available in your development environment require Embedded Coder®.

    For instructions on installing MathWorks® products, see the MATLAB installation documentation. If you have installed MATLAB and want to see which other MathWorks products are installed, in the MATLAB Command Window, enter ver.

  2. Identify an existing MATLAB function or create a new MATLAB function for which you want the code generator to replace code.

Choose a Code Replacement Library

If you are not sure which library to use, explore available libraries.

Configure Code Generator To Use Code Replacement Library

  1. Configure the code generator to apply a code replacement library during code generation for the MATLAB function. Do one of the following:

    • In a project, on the Custom Code tab, set the Code replacement library parameter.

    • In a code configuration object, set the CodeReplacementLibrary parameter.

  2. Configure the code generator to produce only code. Before you build an executable, verify your code replacements. Do one of the following:

    • In a project, in the Generate dialog box, select the Generate code only check box.

    • In a code configuration object, set the GenCodeOnly parameter.

Include Code Replacement Information In Code Generation Report

If you have an Embedded Coder license, you can configure the code generator to include a code replacement section in the code generation report. The additional information helps you verify code replacements. For more information, see Verify Code Replacement Library (Embedded Coder).

Generate Replacement Code

Generate C/C++ code from the MATLAB code. If you configured the code generator to produce a report, generate a code generation report. For example, in the MATLAB Coder app, on the Generate Code page, click Generate. Or, at the command prompt, enter:

codegen -report myFunction -args {5} -config cfg

The code generator produces the code and displays the report.

Verify Code Replacements

Verify code replacements by examining the generated code. Code replacement can sometimes behave differently than you expect. For example, data types that you observe in the code generator input might not match what the code generator uses as intermediate data types during an operation.

Related Topics