Matlab and Mex

On this chapter we learn how to use C/C++ (With Cuda/OpenCl) on matlab command line. Matlab has a tool called Mex that creates a module(DLL/so) from your C/C++ code that can be launched from Matlab console.

This is cool because it allows you to gather data from Matlab and exercise our functions with it.

Mex Setup

First we need to configure mex to use the compiler installed on your machine. Just type mex -setup and click on the link mex -setup C++.

Mex Hello World

Create a mex function on C that print some messages and sum the 2 parameters.

Compiling and loading the function on matlab.

If you observe on your file sysem a file with extension mexa64(Depend on your system) will be created. It's just a simple module (DLL on windows or SO on linux)

Also "mex" is just a wrapper function that will use gcc behind the scenes. You could for instance pass compile flags to help you debug/profile. Also when you are in doubt on what mex is doing just pass the -v option. Also mex can be called from the linux console

Debugging with Mex

GDB on console

It's possible to use gdb to debug mex functions if you load matlab through gdb. This is not the coolest way (using console) but it show the steps necessary to do the same on eclipse.

1) Run matlab with the -Dgdb option this will open gdb

2) From gdb

3) From matlab enable mex debugging and call your function

4) Now when you execute the function it will switch back to gdb where you can break at your function

More realistic use case

Here we're creating a mex function that will serve as a bridge for some matrix 2d implementation. What you can notice here is that we query the input parameters dimensions with the functions mxGetN and mxGetM. Also we check if the inputs has a particular type (float/single) with mxIsSingle and checking if the input is not a complex number with mxIsComplex

This function is wrapping this naive matrix 2d implementation.

Last updated

Was this helpful?