mex 的目的
通過C/C++語言編寫代碼,在Matlab中將其編譯成mex文件主要可以做以下幾方面的事情:
1、加快程序的執行速度. Matlab在for上如老牛拉車的速度確實讓人抓狂.
2、將Matlab作為C++的開發調試環境.尤其是有大量數據需要處理時,用Matlab觀察其中間結果十分方便.
3、據稱可以彌補Matlab硬件設備接口的薄弱環節.
今天寫了第一個使用MEX.
一個簡單的對Matlab普通數值矩陣的操作.
其中Matlab規定的與操作系統版本有關的mwSize,mwIndex, size_t在32位系統上其實本質上就是int,所以
一律用int代替.
#include "mex.h" #include void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { int i,j,k; int index; double* pr=NULL; double* pi=NULL; int M,N; int ndim; int dims[2]; for (i=0;i { if ((mxIsDouble(prhs[i]))&&(mxGetNumberOfDimensions(prhs[i])==2)) { pr=mxGetPr(prhs[i]); pi=mxGetPi(prhs[i]); M=mxGetM(prhs[i]); N=mxGetN(prhs[i]); ndim=mxGetNumberOfDimensions(prhs[i]); mexPrintf("變量%d:\n",i); for (j=0;j { dims[0]=j; for (k=0;k { dims[1]=k; index=mxCalcSingleSubscript(prhs[i],ndim,dims); if (pi==NULL) { mexPrintf("%6.2f",pr[index]); } else { mexPrintf("%6.2f+ %6.2fj",pr[index],pi[index]); } } mexPrintf("\n"); } } else { mexPrintf("input NUMB %d matrix is not 2 dims&double numerical array\n",i); } } }
Result:
>>mex test.cpp >> test(a,b,c)變量0: 0.35 0.62 0.83 0.20 0.47 0.59 0.25 0.35 0.55變量1: 0.92 0.38 0.53 0.57 0.29 0.57 0.78 0.47 0.76 0.08 0.93 0.01 0.75 0.05 0.13 0.34變量2: 0.16+ 0.87j 0.60+ 0.43j 0.45+ 0.14j 0.83+ 0.85j 0.11+ 0.08j 0.79+ 0.08j 0.26+ 0.91j 0.08+ 0.87j 0.54+ 0.62j 0.96+ 0.24j 0.31+ 0.40j 0.65+ 0.18j 0.23+ 0.58j 1.00+ 0.35j 0.00+ 0.12j 0.53+ 0.26j 0.69+ 0.26j 0.91+ 0.55j 0.08+ 0.51j 0.77+ 0.18j 0.17+ 0.80j 0.75+ 0.15j 0.15+ 0.14j 0.44+ 0.40j 0.82+ 0.24j >> help test