80 likes | 255 Views
Mex. Introduction to MEX. MEX = Matlab EXecutable Dynamically Linked Libraries Used like a .m function Written in C (or Fortran). Why MEX. To speed up slow functions To gradually convert from Matlab to C Convert single functions at a time and test incrementally
E N D
Introduction to MEX • MEX = MatlabEXecutable • Dynamically Linked Libraries • Used like a .m function • Written in C (or Fortran)
Why MEX • To speed up slow functions • To gradually convert from Matlab to C • Convert single functions at a time and test incrementally • To use existing C code with Matlab
Components of MEX-files-mexArray There are a number of issues that need to be understood in order to write your own C MEX-files. • The source code for a MEX-file consists of • Computational routine - which contains the actual code that you want implemented in the MEX-file. It is called by the gateway routine (for short MEX-files, the computational routine code can be included in the gateway). • Gateway routine - which interfaces the computational routine with MATLAB: It calls the computational routine • All C MEX-file source code must contain the statement #include "mex.h"so that the entry point and the interface routines are declared properly. • The entry point to the gateway routine must be named mexFunction. This function acts similarly to the function main() in a standalone C program, in that it is where the function MEX-file starts executing when MATLAB calls it. void mexFunction(intnlhs, mxArray *plhs[], …intnrhs, const mxArray *prhs[])
Mex features • You can access data in the context of the calling function • You can call Matlab functions from MEX functions • C-MEX functions can access any type of data that Matlab uses • It is important that you NOT use malloc(), calloc(), etc. • Use mxCalloc() or mxMalloc • Also, you must free up variables when you are done • Use mxDestroyArray • Do not use this on the input arguments • It is possible to allocate static memory • You should also register an exit function if you do
Example #include "mex.h“ void mexFunction(intnlhs, mxArray *plhs[], intnrhs, const mxArray *prhs[]) { mexPrintf("Hello world\n"); }
Imp Mex functions • Array creation • mxCreateNumericArray, mxCreateCellArray, mxCreateCharArray • Array access • mxGetPr, mxGetPi, mxGetM, mxGetData, mxGetCell • Array modification • mxSetPr, mxSetPi, mxSetData, mxSetField • Memory management • mxMalloc, mxCalloc, mxFree, mexMakeMemoryPersistent, mexAtExit, mxDestroyArray, memcpy • Others • mexErrMsgTxt , mexCallMATLABmexPrintf , mexGetArray ….
References • www.mathworks.com • www.google.com