如何使用Matlab矩阵输入形成C ++ 2D数组?

时间:2014-02-11 17:48:23

标签: c++ arrays matlab matrix mex

我正在尝试使用Matlab MEX函数构建一些C ++源代码。我有一个Matlab格式输入(矩阵格式传递给*prhs[],如下所示)。当它传递给mexFunction时,我想将它存储为C ++ 2D数组格式。我写了一些代码如下,但无法编译。你能提一些建议吗?非常感谢。 A.

void mexFunction(
        int          nlhs,
        mxArray      *[],
        int          nrhs,
        const mxArray *prhs[])
{ 

    unsigned int** raster;

    col_rast = mxGetN(prhs[0]);
    row_rast = mxGetM(prhs[0]);

    raster = mxCalloc(col_rast , row_rast ); // Sorry, I missed this line when copy and paste.

    // Convert the matrix into a 2D C array
    for (int col=0; col < col_rast; col++) {
        for (int row=0; row < row_rast; row++) {
            raster[col][row] = mxGetPr(prhs[0])[row+col*row_rast]; 
     }

} 

编辑1:

错误是:

错误C2440:'=':无法从'void *'转换为'unsigned short '         从'void '转换为指向非'void'的指针需要显式转换

编辑2:

但Matlab内置示例(arrayFillSetData.c)的类似实现没有问题:

#include "mex.h"

/* The mxArray in this example is 2x2 */
#define ROWS 2
#define COLUMNS 2
#define ELEMENTS 4

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    UINT16_T *dynamicData;                        /* pointer to dynamic data */
    const UINT16_T data[] = {2, 3, 2, 1};  /* existing data */
    mwSize index;

    /* Check for proper number of arguments. */
    if ( nrhs != 0 ) {
        mexErrMsgIdAndTxt("MATLAB:arrayFillSetData:rhs",
                "This function takes no input arguments.");
    } 

    /* Create a local array and load data */
    dynamicData = mxCalloc(ELEMENTS, sizeof(UINT16_T));
    for ( index = 0; index < ELEMENTS; index++ ) {
        dynamicData[index] = data[index];
    }

    /* Create a 0-by-0 mxArray; you will allocate the memory dynamically */
    plhs[0] = mxCreateNumericMatrix(0, 0, mxUINT16_CLASS, mxREAL);

    /* Point mxArray to dynamicData */
    mxSetData(plhs[0], dynamicData);
    mxSetM(plhs[0], ROWS);
    mxSetN(plhs[0], COLUMNS);

    /* Do not call mxFree(dynamicData) because plhs[0] points to dynamicData */

    return;
}

编辑3:

我想我发现了这个问题。我将Matlab内置示例从'arrayFillSetData.c'重命名为'arrayFillSetData.cpp';然后发生错误。

arrayFillSetData.cpp(35):错误C2440:'=':无法从'void *'转换为'unsigned short '         从'void '转换为指向非'void'的指针需要显式转换

0 个答案:

没有答案