error C2109: 下标需要数组或指针类型 (MEX, Windows 10)

error C2109: subscript requires array or pointer type (MEX, Windows 10)

我在 Windows 10 上使用 mex 在 MATLAB 中实现 C++ 代码。 我想修改我创建的二维数组的元素,但我一直收到此错误。 以下是代码和错误消息。

#include <omp.h>
#include "mex.h"
#include "matrix.h"

// net.idx_phiz{m}(:,1:num_v) => get_index(net.idx_phiz{m}, num_v)

extern "C" void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
    //receive value and create output variable
    auto& matrix = prhs[0];
    auto& size = prhs[1];
    auto& out = plhs[0];

    //get size
    auto m = mxGetM(matrix);
    auto n = mxGetPr(size)[0];

    //get value
    auto val = mxGetPr(matrix);

    //create output pointer
    out = mxCreateNumericMatrix(m, n, mxDOUBLE_CLASS, mxREAL);
    auto B = (double*)mxGetPr(out);

#pragma omp parallel for schedule(static)
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            B[i][j] = val[i][j];
        }
    }
}

从最后一行开始,我得到如下错误:

error C2109: subscript requires array or pointer type

我查阅了过去的讨论,但它们通常是与 mex 无关的错误 C2109。在此先感谢您。

这一行不正确,Bval 是指向 double 的指针,因此不能被索引两次,只能被索引一次。

B[i][j] = val[i][j];

将 MATLAB 数组中的数据视为一维数组,其中逻辑数组的列堆叠在一起。给定 m 行和 n 列,可以使用 i + m*j 获得矩阵元素 (i,j) 在内存中的位置。因此,您的复制操作应为:

B[i + m*j] = val[i + m*j];

但是,上述可能会导致问题,因为 n 是由第二个参数给出的,并且不能保证输入矩阵的列数比多。您需要添加一个显式测试来验证 matrix 至少有 n 列,并且它是一个双值矩阵(例如,如果它是 single 类型也会越界读取,因为 mxGetPr 总是 returns 指向 double 的指针,无论数组中的数据实际是什么。