Integrating GPU Coder™ into Simulink®

This example shows how to integrate GPU Coder™ into Simulink®. While GPU Coder is not supported for Simulink blocks, you can still leverage GPUs in Simulink by generating a dynamic linked library (dll) using GPU Coder and then integrating it into a Simulink block using coder.ExternalDependency APIs. Sobel edge detection is used as an example to demonstrate this concept.

Computer Vision Toolbox™ to use the video reader and viewer used in the example.

Create a New Folder and Copy Relevant Files

The following line of code creates a folder in your current working folder (pwd), and copies all the relevant files into this folder. If you do not want to perform this operation or if you cannot generate files in this folder, change your current working folder.

gpucoderdemo_setup('gpucoderdemo_in_simulink');

Verify the GPU Environment

Use the coder.checkGpuInstall function and verify that the compilers and libraries needed for running this example are set up correctly.

Generate a DLL for the function

To run this function on the GPU from Simulink, generate a shared library by using GPU Coder and call the generated code (library) from Simulink by using coder.ExternalDependency APIs. Copy the generated library to top level directory.

Before generating C/CUDA code, you should first test the MEX function in MATLAB® to ensure that it is functionally equivalent to the original MATLAB code and that no run-time errors occur.

Define coder.ExternalDependency API to Invoke the Generated Code

The SobelAPI.m is a class that defines the API to invoke the generated DLL. Most of this function is a standard template. The method of interest is SobelAPI.sobelEdge, which is called to execute the DLL. This function simply invokes the sobelEdge DLL through a coder.ceval call.

Create a Simulink Model that Integrates the API to the DLL

In Simulink, create a MATLAB function block that calls SobelAPI.sobelEdge. This is equivalent to executing the GPU coder generated DLL code. Thus, when the MATLAB function block executes, this DLL will run on your host machine's GPU. And similarly for code-generation from Simulink, the CUDA code will be invoked. The Simulink model uses a video reader and a video display to show the effect of the algorithm.