Presentation is loading. Please wait.

Presentation is loading. Please wait.

Mex. Introduction to MEX MEX = Matlab EXecutable – Dynamically Linked Libraries – Used like a.m function – Written in C (or Fortran)

Similar presentations


Presentation on theme: "Mex. Introduction to MEX MEX = Matlab EXecutable – Dynamically Linked Libraries – Used like a.m function – Written in C (or Fortran)"— Presentation transcript:

1 Mex

2 Introduction to MEX MEX = Matlab EXecutable – Dynamically Linked Libraries – Used like a.m function – Written in C (or Fortran)

3 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

4 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(int nlhs, mxArray *plhs[], … int nrhs, const mxArray *prhs[])

5 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

6 Example #include "mex.h“ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mexPrintf("Hello world\n"); }

7 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, mexCallMATLAB mexPrintf, mexGetArray ….

8 References www.mathworks.com www.google.com


Download ppt "Mex. Introduction to MEX MEX = Matlab EXecutable – Dynamically Linked Libraries – Used like a.m function – Written in C (or Fortran)"

Similar presentations


Ads by Google