通过
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调用的函数名
),写入下面代码
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");
}
3.
编译
C++函数为
MEX函数
将
ResizeArray.cpp放在
MATLAB当前目录中,在
MATLAB中输入
mex ResizeArray.cpp,编译成功后将会生成
ResizeArray.mexW32
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, selRows, selCols);
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!