Main Content

Generate Code by Using the GPU Coder App

This example shows how to generate CUDA® code from a MATLAB® function by using the GPU Coder™ app. The entry-point function is a MATLAB implementation of the Mandelbrot set algorithm. This example uses the GPU Coder app to generate CUDA code that can run on an NVIDIA® GPU. For an example that shows how to generate code programmatically, see Generate Code Using the Command Line Interface.

Verify the GPU Environment

This example requires:

  • A CUDA-enabled NVIDIA GPU with a compatible driver

  • A compatible compiler on the host machine

For more information about the hardware and software required for GPU Coder, see Installing Prerequisite Products. To set up the compiler, see Setting Up the Prerequisite Products.

To verify that the compilers and libraries necessary to run this example are set up correctly, use the coder.checkGpuInstall function:

envCfg = coder.gpuEnvConfig("host");
coder.checkGpuInstall(envCfg);
Compatible GPU           : PASSED 
CUDA Environment         : PASSED 
	Runtime   : PASSED 
	cuFFT     : PASSED 
	cuSOLVER  : PASSED 
	cuBLAS    : PASSED 
Host Compiler            : PASSED 

The output above is an example of a call to coder.checkGpuInstall. The output may be different when you run this code.

Examine Mandelbrot Entry-Point Function

The Mandelbrot set is the region in the complex plane that consists of the values z0 for which the trajectories defined by

zk+1=zk2+z0,k=0,1,...

remain bounded at k. The figure shows the overall geometry of the Mandelbrot set. This view does not have the resolution to show the detailed structure of the fringe outside the boundary of the set.

The Mandelbrot set.

The mandelbrot_count_start.m entry-point function contains a vectorized implementation of the Mandelbrot set based on the code in Experiments with MATLAB by Cleve Moler.

type mandelbrot_count_start.m
function count = mandelbrot_count_start(maxIterations,xGrid,yGrid) 
% Copyright 2024 The MathWorks, Inc. 

z0 = complex(xGrid, yGrid);
count = ones(size(z0));

z = z0;
for n = 0:maxIterations
    z = z.*z + z0;
    inside = abs(z)<=2;
    count = count + inside;
end
count = log(count);

Prepare the Entry-Point Function for Code Generation

To check for issues related to code generation, add the %#codegen directive at the top of the mandelbrot_count_start function. This directive causes the Code Analyzer in the MATLAB Editor to flag warnings and errors related to code generation.

function mandelbrot_count_start(maxIterations,xGrid,yGrid) %#codegen

In the top-right corner of the MATLAB Editor, the Code Analyzer displays the No warnings found icon which indicates that the analyzer did not detect errors, warnings, or opportunities for improvement in the code.

To map the entry-point function to a CUDA kernel, add the coder.gpu.kernelfun pragma to the function. During code generation, GPU Coder analyzes functions with the coder.gpu.kernelfun pragma and tries to map computations to the GPU.

After inserting the %#codegen directive and the coder.gpu.kernelfun pragma, save the function as mandelbrot_count.m.

type mandelbrot_count.m
function count = mandelbrot_count(maxIterations,xGrid,yGrid) %#codegen

% Copyright 2016-2024 The MathWorks, Inc. 

z0 = complex(xGrid, yGrid);
count = ones(size(z0));

% Map computation to GPU.
coder.gpu.kernelfun;

z = z0;
for n = 0:maxIterations
    z = z.*z + z0;
    inside = abs(z)<=2;
    count = count + inside;
end
count = log(count);

Test the Functionality of the Entry-Point Function

The mandelbrot_test.m script generates a 1000-by-1000 grid of real and imaginary parts between the limits xlim and ylim. It calls mandelbrot_count with this grid and plots the resulting Mandelbrot set.

type mandelbrot_test.m
% Copyright 2024 The MathWorks, Inc.

maxIterations = 500;
gridSize = 1000;
xlim = [-0.748766713922161,-0.748766707771757];
ylim = [0.123640844894862,0.123640851045266];

x = linspace(xlim(1),xlim(2),gridSize);

y = linspace(ylim(1),ylim(2),gridSize);

[xGrid,yGrid] = meshgrid(x,y); 

%% Mandelbrot computation in MATLAB

count = mandelbrot_count(maxIterations,xGrid,yGrid);

%% Show

figure(1)
imagesc(x,y,count);
colormap([jet();flipud(jet());0 0 0]);
axis off
title('Mandelbrot set with MATLAB');

Run the mandelbrot_test script to plot the Mandelbrot set in the boundaries of xlim and ylim.

mandelbrot_test

Figure contains an axes object. The hidden axes object with title Mandelbrot set with MATLAB contains an object of type image.

Generate Code with the GPU Coder App

In the MATLAB Toolstrip, in the Apps tab, in the Code Generation section, click GPU Coder to open the app. Alternatively, open the app by entering gpucoder at the MATLAB command line:

gpucoder

The app opens the Create GPU Coder Project dialog box. You can create a new GPU Coder project or open an existing one. The GPU Coder app saves projects with the .coderprj extension. Specify the name as mandelbrot_count.coderprj and click OK. The GPU Coder app opens the GPU Coder tab, which contains the options to prepare for code generation, generate code, run generated code, and open code generation reports.

GPU Coder tab of the MATLAB toolstrip

The GPU Coder app also opens a GPU Coder panel including:

  • The Next Steps section, which summarizes the next step in the code generation process.

  • The Input section, which contains the inputs to the code generation process.

  • The Output section, which lists the output of the code generation process. This section populates when you generate code.

The Next Steps section indicates that you must add an entry-point function.

GPU Coder panel showing the first step is to add an entry-point function

Add the mandelbrot_count Entry-Point Function

To add an entry-point function, in the GPU Coder panel, click Add Entry Points. Alternatively, in the toolstrip, click Entry Points. In the Entry Point pane that opens, specify the entry-point function as mandelbrot_count.

Define Input Types

GPU Coder must determine the data types of the variables in your MATLAB code before it generates code. Therefore, you must specify the data types of the input variables for your entry-point functions. You can specify the input data types by using one of these methods:

  • Providing a script that calls the entry-point functions in your project

  • Executing the entry-point function by using commands in the MATLAB Command Window

  • Entering the input data types manually

In this example, use the script mandelbrot_test to define the input types for mandelbrot_count. In the Entry Points tab, in the Automatically Define Input Types drop-down menu, select Using Script. Enter the script name, mandelbrot_test, and click the Run button. The app adds the input types to the Entry Points section including their dimensions and data types.

Entry Points pane showing the data types and dimensions of the inputs to mandelbrot_count

Generate CUDA Code

In the GPU Coder tab, you can configure how you want GPU Coder to build the generated code. In the Prepare section, set Output type to MEX.

To generate the MEX file, click Generate Code and Build. The Output section of the GPU Coder panel shows code generation is successful and links to the generated code folder and report.

Output section of the GPU Coder panel

To compare the generated code with the original MATLAB function, see Verify Correctness of the Generated Code.

See Also

Apps

Functions

Objects

Topics