1
votes

I'm an experienced MATLAB user but totally new to C and MEX files. I have a complex program written in C that I need to call from within MATLAB. The program consists of a few dozen files in a folder, including one called main.c that processes inputs from the command line passes the results to other classes that do the actual calculations.

Normally, to install this program from the command line, I would run ./configure, make at the UNIX command prompt. Then, to run the program, ./runMyProgram -f input_file.txt -p some_parameters. The program takes a text file consisting of a list of numbers as input and prints a table of results in the command window. I want to feed the program a MATLAB array (instead of a .txt file) and get back an array (instead of a printed table of results).

I have read the MEX documentation from The Mathworks (which I found rather opaque), as well as some other "tutorials", but I am totally lost - the examples are for very simple, single-file C programs and don't really discuss how to handle a larger and more complicated program. Is it enough to replace the main.c file with a MEX file that does the same things? Also, how do I compile the whole package within MATLAB?

I would be grateful for any plain-English advice on where to start with this, or pointers to any tutorials that deal with the subject in a comprehensible way.

1
Look here: shawnlankton.com/2008/03/…. This helped me tremendously when I was starting out.Justin
It's a pain to build complex MEX files. Don't expect it to be a pretty experience. :)Memming
Why don't you just use system or similar to run the program from MATLAB and then parse the output? That way, you don't have to write any C code or mess with the program's code (and you won't have to do it again if the program gets updated by its author).wakjah
@wakjah: Didn't think of that... great idea. Though I would still like to learn how to deal with MEX files for the sake of my own knowledge :-)dannyhmg

1 Answers

2
votes

Yes. Normally replacing a main.c file with MEX file is the process. In your case since you already have complex build setup, it might be easier to build a library and then build a separate mex file which just links against this library. This will be much easier than building the whole thing using mex command. If you export the function you need to call from your library, you can call it from your mexFunction. mexFunction can do all the creation and reading of mxArrays. A simple sample mexFunction can be,

#include "mex.h"
// Include headers for your library

void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
   void* x = mxGetData(prhs[0]); // Assume one input. Check nrhs
   plhs[0] = mxCreateDoubleMatrix(10,10,mxREAL); // Create 10x10 double matrix for output
   void* y = mxGetData(plhs[0]);
   yourLibraryFunction(x, y); // Read from x and write to y. Pass sizes in if needed
}