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 responses to “MEX file generator”
[…] I’ve updated mexme accordingly, so you can generate cross-platform MEX files with only a rudimentary understanding of C. […]
[…] chokes on. But it’s pretty straightforward to code this up in C and wrap as a MEX file (see also this). With this solution in hand the initial test lasts 14s with a blocksize of 500,000, and takes less […]