wiki:adherelinux/mex

=matlab 工具 mex=

*mex 主要是讓Maltab和C語言、Fortran語言作溝通,Matlab程式中把引數對應好就可以利用C、Fortran幫我們做運算。

進入mexfunction我們就可以寫C、Fortran程式了。然而若可以寫C程式,這樣的話我們也可以利用GPU來做運算。

mexFunction的框架如下: void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

....可以撰寫C、Fortran程式

}

nlhs(Type = int): number of "left hand side" arguments (呼叫函式時,等號左邊的變數數目,即 plhs 之個數)

plhs(Type = array of pointers to mxArrays): actual output arguments (呼叫函式時,等號左邊之變數本體)

nrhs(Type = int): number of "right hand side" arguments (呼叫函式時,等號右邊的變數數目,即 prhs 之個數)

prhs(Type = const array of pointers to mxArrays): all of the pointers to the mxArrays of input data for instance (呼叫函式時,等號右邊之變數本體

以下舉例一個範例。利用Matlab輸入兩個向量作相加。

程式碼如下:檔名為add.c

#include "mex.h" void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) {

int i, j, mA, nA, mB, nB, nMatSize;
double *A, *B, *C;
/*input_check */
if (nrhs != 2)

mexErrMsgTxt("The input must 2");

if (nlhs != 1)

mexErrMsgTxt("The input must 1");

mA = mxGetM(prhs[0]);
nA = mxGetN(prhs[0]);
mB = mxGetM(prhs[1]);
nB = mxGetN(prhs[1]);

printf("mA= %d\n",mA);

if (mA != mB
nA != nB)

mexErrMsgTxt("The size must identical") ;

/*output to buffer*/
plhs[0]=mxCreateDoubleMatrix(mA,nA,mxREAL);
/*get value*/
A = mxGetPr(prhs[0]);
B = mxGetPr(prhs[1]);
C = mxGetPr(plhs[0]);
/*sum*/
nMatSize = mA * nA;
for (i=0; i<nMatSize; i++){

C[i] = A[i] + B[i];

}
/*result*/
mexPrintf("ending");

}

how to compile and run 執行MATLAB程式在命令端下

mex add.c
a = [1 2 3 4];
b = [1 2 3 4];
c = add(a,b)

mA=1
ending
c =
2 4 6 8

Last modified 14 years ago Last modified on Jul 19, 2010, 2:47:36 PM