Accelerating MATLAB Code Using Codegen and Mex Files



The most useful function when accelerating MATLAB code is the codegen command. This guide will briefly show how to use the codegen command to turn MATLAB code into C MATLAB Executables or C MEX files. You can execute these MEX files as if they were functions from anywhere in MATLAB.

Introduction to Mex Files

You can call your own C, C++, or Fortran subroutines from the MATLAB® command line as if they were built-in functions. These programs, called binary MEX-files, are dynamically linked subroutines that the MATLAB interpreter loads and executes. The MEX-file contains only one function or subroutine, and its name is the MEX-file name. To call a MEX-file, use the name of the file, without the file extension.

Why use Mex files

The performance of code that uses mex files can increase by up to a factor of 10, depending on the code. For example, code that thresholds an image (i.e. bw = image(:,:1)>30 && image(:,:,1)<150 ) has been shown to increase in speed by up to 8x. Loop performance is also greatly affected by code generation.

This example compares the performance between a buoy detection algorithm with and without a mex file.

Open Example

How to Generate a MEX file using codegen


As with most code generation related workflows in MATLAB and Simulink, a compiler is necessary.

MATLAB® Coder™ automatically locates and uses a supported installed compiler. For the current list of supported compilers, see Supported and Compatible Compilers on the MathWorks® Web site.

You can use mex -setup to change the default compiler. See Changing Default Compiler.

To determine if your compiler is set up correctly, use the following example in the documentation:

Build an Executable Mex File

Step 1: Insert Codegen Directive

Add the %#codegen directive (or pragma) to your function after the function signature to indicate that you intend to generate code for the MATLAB® algorithm.

function bw = thresholdImage(img,thresholds)
   bw = logical(... % red threshold

Adding this directive instructs the MATLAB code analyzer to help you diagnose and fix violations that would result in errors during code generation. If there are functions that are not supported for code generation, this directive will allow the MATLAB code analyzer to tell you.

Alternatively, you could use the following documentation to determine pre-emptively if a function is supported for code generation.

Documentation: Features and Functions Supported for Code Generation

Step 2: Run the codegen command

Use the codegen command to generate code out of the MATLAB Function. If the function has arguments, the data types and sizes of the input and output arguments need to pre-specified so that the code generation process knows what the function should expect.

codegen thresholdImage -args {zeros(480,640,3,'uint8'),zeros(3,2,'uint8')}


Full File vs. Individual Function Code Generation

There are two ways to use mex files.

  1. Take everything except non-codegen supported functions and convert it into mex files
  2. Find functions that are computationally expensive using the MATLAB Profiler and/or tic and toc. Convert these functions into mex files.

Full File Code Generation

Make sure that all of the code is supported for code generation, then generate code for everything.

Open Example

Profile, then Individual Function Code Generation

Profile code using the "Run and Time" button in the MATLAB Editor. The Profiler will run the function and return the names of the functions that are taking the most time to execute. In the following example, the thresholdImage function is taking the most time to execute at 2.363s.

Open Example: Before Code Generation

After implementing codegen on the function,
the resulting profiler shows that the execution time is much less at
0.319s. According to this profiler, the threshold code has increased in speed by
about 7x!

Open Example: After Code Generation

Timer Objects with Code Generation

If you would like to run your code on a schedule (i.e. buoy detection every 0.1 seconds), you need to use timer objects. Timer Objects are not supported for code generation.

A sub-function needs to be created to handle the algorithm, which can be converted into a mex file.

Open Example: Timers

Other uses for codegen

MATLAB Coder's codegen command can also turn MATLAB code into executables or libraries. Executables could just be run from the OS bash prompt and libraries could be integrated into custom IDEs.