MATLAB调用C/C++函数的方法

来源:互联网 发布:淘宝花呗怎么开通不了 编辑:程序博客网 时间:2024/04/29 22:40

原文地址http://blog.sciencenet.cn/home.php?mod=space&uid=43777&do=blog&id=320103

通过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" //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"); }

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,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!

0 0