CMake/MatlabMex

From KitwarePublic
Jump to navigationJump to search

What are Matlab mex files?

Mex files are functions written in C or C++ that are callable in the Matlab scripting language in a Matlab interpretor. Matlab is a 'Matrix Laboratory', a general purpose scientific scripting language owned by The Mathworks company.

Details of writing mex files can be found in the Matlab documentation.

Before you begin

Matlab is a language with good syntax for working with matrices, a variety of functions, excellent documentation, and it is ubiquitous throughout the academic, scientific community. On the other hand, it is extremely slow, has poor memory utilization, is prohibitively expensive, sees little use outside academia, has a language syntax that is only good for simple procedural scripting, is closed source, and has numerous bugs. Writing mex files is often an attempt to address some of these limitations -- speed and memory usage. However, it is a difficult and not very elegant solution. Instead, researchers should consider using superior products, such as SciPy, SciLab, Sage, or Octave.

Why would you want to use CMake for creating mex files?

If you have a very small project that consists of only a single source code file that does not link to other libraries, then simply using the mex compiler at the command line is all that you need. However, if your project is non-trivial, there are many advantages to using CMake. A make system allows you to recompile and link only the files that change during development and to perform parallel builds. CMake provides a configuration system finding libraries on systems. The are many advantages to organizing and controlling the build system in a simple and powerful way, which CMake can do, among other things.

How do you use CMake with Matlab?

Background on the Matlab mex "compiler"

Matlab comes with a mex "compiler". It is not a true compiler, but a frontend build script to the compiler of your choice. On MS Windows it is a perl script, and on Unix-like systems it is a shell script, although they have the same user interface. Issuing

mex -setup

allows you to setup the configuration file the mex script uses to determine which compiler it will use, the flags it will pass, etc.

mex -v 

shows the compiler and settings the build script is using.

Hello World Example

More complex example: ITK based image reader

Platform specific issues