Main Content

Code Generation from Simulink Models by Using GPU Coder

GPU Coder™ produces CUDA® C++ code from Simulink® models containing MATLAB Function blocks. The generated code and executable can be used for rapid prototyping on GPUs such as NVIDIA® Tesla® and NVIDIA Tegra®. Code generation reports and traceability allows you to view and analyze the generated code. The basic steps for CUDA Code generation by using GPU Coder are:

  • Create or open a model

  • Configure the model for code generation by selecting the solver, language, toolchain, and other GPU-specific configuration parameters

  • Build the model

Example: Sobel Edge Detection

The Sobel edge detection algorithm performs a 2-D spatial gradient operation on a grayscale image. This operation emphasizes the high spatial frequency regions which corresponds to the edges of the input image. The algorithm computes the horizontal gradient (H) and the vertical gradient (V) of the input image by using two orthogonal filter kernels (k and k'). After the filtering operation, the algorithm computes the gradient magnitude and applies a threshold to find the regions of the images that are considered to be edges.

k = single([1 2 1; 0 0 0; -1 -2 -1]);
H = conv2(single(grayImage),k, 'same');
V = conv2(single(grayImage),k','same');
E = sqrt(H.*H + V.*V);
edgeImage = uint8((E > threshold) * 255);

MATLAB peppers.png test image and its edge detected output.

Create Edge Detection Model

  1. Create a new Simulink model and insert two MATLAB Function blocks from the User-Defined Functions library.

  2. Add a Constant (Simulink) block and set its value to 0.4. Add a From Multimedia File (Computer Vision Toolbox) block from the Computer Vision Toolbox™ library.

  3. Open the Block Parameters dialog for the From Multimedia File block and set the File name parameter to rhinos.avi.

    Set the Image signal parameter to One multidimensional signal.

  4. Add two Video Viewer (Computer Vision Toolbox) blocks from the Computer Vision Toolbox library to the model.

    Simulink model containing blocks for implementing edge detection algorithm.

  5. Double-click on one of the MATLAB Function blocks. A default function signature appears in the MATLAB Function Block Editor.

  6. Define a function called sobel, which implements the Sobel edge detection algorithm. The function header declares grayImage and threshold as an argument to the sobel function, with edgeImage as the return value. Save Editor document to file.

    function edgeImage  = sobel(grayImage,threshold)   %#codegen
    % Define Kernel for Sobel edge detection
    k = single([1 2 1; 0 0 0; -1 -2 -1]);
    % Detect Edge
    H = conv2(single(grayImage),k, 'same');
    V = conv2(single(grayImage),k','same');
    E = sqrt(H.*H + V.*V);
    edgeImage = uint8((E > threshold) * 255);

  7. Right-click on the MATLAB Function block and select Block Parameters (Subsystem).

  8. On the Code Generation tab, select Reusable function for Function packaging.

  9. Repeat steps 3 and 4 for the other MATLAB Function block. This block implements the RGB to grayscale conversion prior to the Sobel edge detection operation.

    function gray = RGB2gray(RGB)   %#codegen
    % Convert color image to grey image
    gray = (0.2989 * double(RGB(:,:,1)) + ...
        0.5870 * double(RGB(:,:,2)) + ...
        0.1140 * double(RGB(:,:,3)));
  10. Connect these blocks as shown in the diagram. Save the model as edgeDetection.slx.

    Simulink model showing connection between the blocks.

  11. To test for errors, simulate the model in the Simulink Editor using the Run button on the toolstrip. To see all video frames during simulation, disable the Simulation > Drop Frames to improve Performance option of the Video Viewer block.

    Edge detected output from the Video Viewer block.

Configure the Model for Code Generation

The model configuration parameters provide many options for the code generation and build process.

  1. Open the Configuration Parameters dialog box, Solver pane. To generate CUDA code for the model, you must configure the model to use a fixed-step solver. This option maintains a constant (fixed) step size, which is required for code generation.

    ParameterSettingEffect on Generated Code
    TypeFixed-stepMaintains a constant (fixed) step size, which is required for code generation
    Solverdiscrete (no continuous states)Applies a fixed-step integration technique for computing the state derivative of the model
    Fixed-step sizeautoSimulink chooses the step size

    Snapshot of the configuration parameters dialog showing solver options for simulation.

  2. Select the Code Generation pane. Set the System target file to grt.tlc. You can also use the Embedded Coder® target file ert.tlc.

  3. Set the Language to C++.

  4. Select Generate GPU code. GPU Coder specific options are now visible in the Code Generation > GPU Code pane.

  5. Select Generate code only.

  6. Select the Toolchain. For Linux® platforms select NVIDIA CUDA | gmake (64-bit Linux). For Windows® systems, select NVIDIA CUDA (w/Microsoft Visual C++ 20XX) | nmake (64-bit windows).

  7. On the Code Generation > Interface pane, disable MAT-file logging. The code generator does not support MAT-file logging when generating CUDA code.

  8. On the Code Generation > Report pane, select Create code generation report and Open report automatically.

  9. For the purposes of this example, you can use the default values of the GPU-specific parameters in Code Generation > GPU Code pane.

    GPU Code pane on the configuration parameters dialog of the model.

  10. Click OK to save and close the Configuration Parameters dialog box.

  11. Alternatively, you can use set_param (Simulink) to configure the model parameter programmatically from the MATLAB® command Window. For example,


Generate CUDA Code for the Model

  1. In the Simulink Editor, open the Simulink Coder app.

  2. Generate code.

    Messages appear in the Diagnostics Viewer. The code generator produces CUDA source and header files, and an HTML code generation report. The code generator places the files in a build folder, a subfolder named edgeDetection_grt_rtw under your current working folder.

    You can find the CUDA kernels in the <model_name>_eML_blk_kernel and <model_name>_eML_blk_kernel_c functions. The information within the triple chevrons is the execution configuration for the kernel.

  3. Example of the generated CUDA code.


  • Use of MATLAB Function blocks in Stateflow® charts is not supported.

  • MATLAB Function block does not support all the data types from the MATLAB language. For supported data types, refer to the block documentation.

  • For GPU code generation, the Terminate function required parameter in the Code Generation > Interface pane must be enabled.

See Also


Related Topics