MEX file generator

I just posted a script in Matlab Central that generates a .c file that can be compiled with mex based on a snippet of (purely numeric) C code and a definition of the arguments to the function. In the file description I show how to write a recursive (IIR) filter in 3 lines of C code that can be called from Matlab after compiling with mex. I think that those that write number crunching code in C from time to time will appreciate it, as it automatically writes the nasty bits of mex code for you (the bits involving pointers and calls to mx*), allowing you to focus on the more relevant and straightforward numeric core of the algo.

99% of the time, mex code is designed to replace “the for loop of death”, a nasty bit of .m code that is not vectorizable and that sucks up the CPU. The for loop of death occurs in many problems: ODE solving, parameter inference in HMMs, Markov chain Monte Carlo methods, etc. C can be very effective in these situations. You don’t need to be a C genius to write a for loop and manipulate arrays, and hopefully this code will help you to write MEX files even if, like me, your knowledge of C is very basic.

I tried to replicate the weave functionality of NumPy, which allows you to write inline numeric C code inside of larger functions that use NumPy arrays. mexme does not go that far, and requires more explicit definitions of the inputs and outputs of the C code, but it could be extended to work more like weave, if there is interest for that.

2 thoughts on “MEX file generator

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s