Writing a Matlab MEX function
Matlab November 11th. 2007, 9:55pmThe good thing with Matlab is that it provides excellent library of functions and great felxibility to implement something in very less time. One of the other great things is that you can write your code in another language and run it in the Matlab environment. Matlab’s MEX (Matlab-EXecutable) feature allows C code to compile into a Matlab compatible executable so that it runs much faster than its M-file equivalent. Under Windows the MEX function is compiled into a .dll or win32 binary file. If you are running Matlab in other environments then the function would need to be compiled into an appropriate format:

Usually the Matlab compiler automatically identifies the appropriate format of the target file.
In this example I show a MEX function for calculating the mean of an array. We will then use this function in our Genetic Algorithm to show that it improves the speed of our code. I keep the explanation brief as there are numerous resources elsewhere which explain how to write MEX functions.
The standard interface for a MEX function written C takes the form:

nlhs(Type = int): This paramter represents the number of “left hand side” arguments.
plhs(Type = array of pointers to mxArrays): This parameter is the actual output arguments. As we will see in our example code that, an mxArray is MATLAB’s structure for holding data and each element in plhs holds an mxArray of data.
nrhs(Type = int): Similar to nlhs, this paramter holds the number of “right hand side” arguments.
prhs(Type = const array of pointers to mxArrays): This array hold all of the pointers to the mxArrays of input data.
In a similar fashion our MEX function code for calculating the mean of an array is:

The resulting .dll file runs 40% faster than its .m file equivalent which slightly improves the speed of our Genetic Algorithm.
The bigger window shows profiling with the MEXed code.
- .m file = approx 1 second per generation
- .dll MEX = approx 0.6 seconds per generation
We will move to a complete C++ model in a couple of weeks when we look at a more challenging problem using a self-evolving Prediction Function.
Resources:
