經過MATLAB將C/C++函數編譯成MEX函數,在MATLAB中就能夠調用了。數組
1,首先裝編譯器
Matlab裏鍵入mex -setup,選擇你要編譯C++的編譯器函數
2,寫C++函數
函數的形式必須是
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
nlhs: 輸出參數個數
plhs:輸出參數列表
nrhs:輸入參數個數
prhs:輸入參數 列表
,不過函數名能夠隨便取的。注意:保存的文件名就是未來在MATLAB中調用的函數名,而不是 這裏的函數名。
下面給出一個例子,目的是想截取數組的部分元素組成新的數組
輸入參數3個,目標數組,截取的行(向量),截 取的列(向量)
輸出參數2個,截取後數組,數組維數信息
在函數中展現瞭如何傳入傳出參數,以及若是從參數列表中取出每個參 數,MATLAB數據和C++數據的互相轉換,還有一些輸出函數等。
新建一個ResizeArray.cpp文件(ResizeArray將做爲MATLAB調用的函數名),寫入下面代碼
#include "mex.h"
//author: 汪幫主 2010.05.05
//MATLAB調 用形式: [resizedArr, resizedDims] = ResizeArray(arr, selRows, sekCols)
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 3)
{
mexErrMsgTxt("參數個數不正確!");
}
int rowNum = mxGetM(prhs[0]);
int colNum = mxGetN(prhs[0]);
double* pArr = (double*)mxGetPr(prhs[0]);
//獲得選擇的行列信息
//不管是行向量仍是列向量均支持
double* pSelRows = (double*)mxGetPr(prhs[1]);
double* pSelCols = (double*)mxGetPr(prhs[2]);
int selRowsRowNum = mxGetM(prhs[1]);
int selRowsColNum = mxGetN(prhs[1]);
if (selRowsRowNum!=1 && selRowsColNum!=1)
{
mexErrMsgTxt("行參數不正確!");
}
int selRowsNum = selRowsRowNum*selRowsColNum;
int selColsRowNum = mxGetM(prhs[2]);
int selColsColNum = mxGetN(prhs[2]);
if (selColsRowNum!=1 && selColsColNum!=1)
{
mexErrMsgTxt("列參數不正確!");
}
int selColsNum = selColsRowNum*selColsColNum;
plhs[1] = mxCreateDoubleMatrix(2, 1, mxREAL);
double* resizedDims = (double*)mxGetPr(plhs[1]);
resizedDims[0] = selRowsNum;
resizedDims[1] = selColsNum;
plhs[0] = mxCreateDoubleMatrix(selRowsNum, selColsNum, mxREAL);
double* pResizedArr =(double*)mxGetPr(plhs[0]);
//這裏由於MATLAB中數據得按列優先
#define ARR(row,col) pArr[(col)*rowNum+row]
#define RARR(row,col) pResizedArr[(col)*selRowsNum+row]
for(int ri=0; ri<selRowsNum; ri++)
{
for(int ci=0; ci<selColsNum; ci++)
{
RARR(ri,ci)=ARR((int)pSelRows[ri]-1,(int)pSelCols[ci]-1);
}
}
mexPrintf("OK!\n");
} spa
3,編譯C++函數爲MEX函數
將ResizeArray.cpp放在MATLAB當前目錄中,在 MATLAB中輸入mex ResizeArray.cpp,編譯成功後將會生成ResizeArray.mexW32ci
4,調用函數
arr=[11:19;21:29;31:39;41:49;51:59;61:69];
selRows=[1 3];
selCols=[2:4 5 9];
[rarr,rdims]=ResizeArray(arr,rows,cols);
arr 中數據:
11 12 13 14 15 16 17 18 19
21 22 23 24 25 26 27 28 29
31 32 33 34 35 36 37 38 39
41 42 43 44 45 46 47 48 49
51 52 53 54 55 56 57 58 59
61 62 63 64 65 66 67 68 69
rarr 中數據:
12 13 14 15 19
32 33 34 35 39
rdims爲:
2
5編譯器
OK,done!io