Using mex-files with Matlab R2006b ================================== .. highlight:: matlab Nested for loops can slow down your Matlab simulations considerably. The idea is to rewrite these parts of your code in C++ and build executable "mex"-code from it. Setting up the build process ---------------------------- From the Matlab command line run:: > mex -setup When asked, choose gccopts.sh for a linux system. Overview -------- We intend to replace a ``‹function›.m`` by an executable ``‹function›.mexglx`` for linux by first rewriting the implementation of ``‹function›.m`` in a C++ file ``‹function›.cpp`` and then compiling it. Mex basics ---------- ``‹function›.cpp`` must first ``#include "mex.h"`` to be able to use all C-functions prefixed by ``mx`` or ``mex``. ``‹function›.cpp`` must contain one function called ``mexFunction`` which substitutes the function originally residing in ``‹function›.m``: .. code-block:: c++ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // function implementation } The ``‹function›.cpp`` file can now be compiled on the Matlab command line:: > mex ‹function›.cpp Handling data ------------- The fundamental Matlab type in C is an ``mxArray``. The two arguments to the ``mexFunction`` are the left hand side and right hand side ``mxArrays`` which correspond to the output and input arguments respectively of the ``‹function›.m`` file. ``mxArrays`` can have different types. In Matlab, language type checking and conversion is implicit, while in C++ you have to take care for it. ``mxArrays`` have a size just like Matlab matrices have. Conversely, ``plhs`` and ``prhs`` are C arrays of pointers to ``mxArrays`` with sizes ``nlhs`` and ``nrhs`` respectively. While the``mxArrays`` in prhs are given to you, you are expected to create some ``mxArrays`` and store the pointers in ``plhs``. Some example ``mexFunction``: .. code-block:: c++ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); //create an mxArray double *d = mxGetPr(plhs[0]); //get a pointer to the data d[0] = 0.1811; } This functions, when executed in Matlab always returns 0.1811. Some useful ``mx...`` functions ------------------------------- ``mxGetNumberOfDimensions`` returns the number of dimensions (usually 2) of your matrix. ``mxGetDimensions`` returns an array containing the size of each dimension of a matrix. ``mxGetPr`` returns a pointer to the (real part of the) data of the matrix. ``mxCreateDoubleMatrix`` creates an mxArray for an ordinary matrix of given size. Extensions ---------- ``#include `` to store and load ``.mat`` files. Help ---- The Matlab help concerning mex-files resides here: * Matlab > External Interfaces > Calling C and Fortran Programes from Matlab * Matlab > External Interfaces > Creating C Language MEX-Files * Matlab > C and Fortran Functions - By Category