close
Warning:
Can't synchronize with repository "(default)" (Unsupported version control system "svn": /usr/lib/python2.7/dist-packages/libsvn/_repos.so: failed to map segment from shared object: Cannot allocate memory). Look in the Trac log for more information.
- Timestamp:
-
Jul 17, 2010, 9:17:32 PM (15 years ago)
- Author:
-
adherelinux
- Comment:
-
--
Legend:
- Unmodified
- Added
- Removed
- Modified
-
|
v5
|
v6
|
|
| 4 | 4 | |
| 5 | 5 | 進入mexfunction我們就可以寫C、Fortran程式了。然而若可以寫C程式,這樣的話我們也可以利用GPU來做運算。[[br]] |
| 6 | | 以下舉例一個範例。利用Matlab輸入兩個方陣,作相加。 |
| | 6 | |
| 7 | 7 | mexFunction的框架如下: |
| 8 | 8 | void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) |
| … |
… |
|
| 19 | 19 | prhs(Type = const array of pointers to mxArrays): all of the pointers to the mxArrays of input data for instance (呼叫函式時,等號右邊之變數本體[[br]] |
| 20 | 20 | |
| | 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 | |