| | 21 | 以下舉例一個範例。利用Matlab輸入兩個向量作相加。 |
| | 22 | |
| | 23 | 程式碼如下:檔名為add.c |
| | 24 | |
| | 25 | #include "mex.h" |
| | 26 | void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) |
| | 27 | { |
| | 28 | int i, j, mA, nA, mB, nB, nMatSize; |
| | 29 | double *A, *B, *C; |
| | 30 | /*input_check */ |
| | 31 | if (nrhs != 2) |
| | 32 | mexErrMsgTxt("The input must 2"); |
| | 33 | if (nlhs != 1) |
| | 34 | mexErrMsgTxt("The input must 1"); |
| | 35 | mA = mxGetM(prhs[0]); |
| | 36 | nA = mxGetN(prhs[0]); |
| | 37 | mB = mxGetM(prhs[1]); |
| | 38 | nB = mxGetN(prhs[1]); |
| | 39 | |
| | 40 | printf("mA= %d\n",mA); |
| | 41 | if (mA != mB ||nA != nB) |
| | 42 | mexErrMsgTxt("The size must identical") ; |
| | 43 | |
| | 44 | /*output to buffer*/ |
| | 45 | plhs[0]=mxCreateDoubleMatrix(mA,nA,mxREAL); |
| | 46 | /*get value*/ |
| | 47 | A = mxGetPr(prhs[0]); |
| | 48 | B = mxGetPr(prhs[1]); |
| | 49 | C = mxGetPr(plhs[0]); |
| | 50 | /*sum*/ |
| | 51 | nMatSize = mA * nA; |
| | 52 | for (i=0; i<nMatSize; i++) |
| | 53 | { |
| | 54 | C[i] = A[i] + B[i]; |
| | 55 | } |
| | 56 | /*result*/ |
| | 57 | mexPrintf("ending"); |
| | 58 | } |
| | 59 | |
| | 60 | how to compile and run |
| | 61 | >mex add.c |
| | 62 | >a = [1 2 3 4]; |
| | 63 | >b = [1 2 3 4]; |
| | 64 | >c = add(a,d) |
| | 65 | mA=1 |
| | 66 | ending |
| | 67 | c = |
| | 68 | 2 4 6 8 |
| | 69 | |
| | 70 | |