C/C++ calling Matlab functions
Since many of us use C/C++ to code our GAs, and then use Matlab to plot the results, here’s several simple steps that allow you to call Matlab functions directly from C/C++:
1. Convert the main to mexFunction
mexFunction is the entrance of matlab executable.
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) {
int i;
int argc = nrhs;
char **argv;
argv = new char * [argc];
for (i=0; i<argc; i++) {
int length = mxGetNumberOfElements(prhs[i])+1;
argv[i] = new char [length];
mxGetString(prhs[i], argv[i], length);
}
...
}
Basically, prhs are left elements and plhs are right elements.
e.g. In Matlab
[a,b]=xxx(c,d,e);
a and b are prhs, and nrhs = 2
c, d, and e are plhs, and nlhs = 3
2. Convert printf to mexPrintf
This can be done simply by
"#define printf mexPrintf"
3. Error message: mexErrMsgTxt will show text in red (default) in Matlab.
mexErrMsgTxt("blah blah blah");
4. Include “mex.h” everywhere you call mex functions.
mex.h can be found under the maltab directory.
5. To call a matlab function, use mexCallMATLAB
For example, to call a = f(b), where a is a double and b is a 1×2 matrix, the code looks like:
mxArray *plhs, *prhs; prhs = mxCreateDoubleMatrix(1, 2, mxREAL); double *ptr = mxGetPr(prhs); ptr[0] = b; ptr[1] = c; mexCallMATLAB(1, &plhs, 1, &prhs, "f"); a = *mxGetPr(plhs); mxDestroyArray(plhs); mxDestroyArray(prhs);
6. Compile the transferred code into mex (in Matlab)
mex -f /usr/local/matlab/bin/cxxopts.sh foo.cpp foo1.cpp foo2.cpp .....
cxxopts.sh are needed to let matlab know that you are doing c/c++.
It can be found under the matlab directory. The 1st name will be used as the library name (foo). In windows, the result is .dll; in Linux, it’s .mexglx.
More mex functions can be found on the MathWorks. Hope that helps.
Posted by admin on January 28th, 2005 under Illigal-blogging
Comments: none
Write a comment