matlab和C如何混编

    技术2022-05-19  54

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

    系统分类:科研笔记|关键词:MATLAB C C++ 调用

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

    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 1921 22 23 24 25 26 27 28 2931 32 33 34 35 36 37 38 3941 42 43 44 45 46 47 48 4951 52 53 54 55 56 57 58 5961 62 63 64 65 66 67 68 69rarr中数据:12 13 14 15 1932 33 34 35 39rdims为:25

    OK,done!


    最新回复(0)