I am using mex to implement C++ codes in MATLAB on Windows 10. I want to modify the elements of a 2D array that I created but I keep getting this error. Below are the codes and the error message.
#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];
}
}
}
From the last line, I get the error as below:
error C2109: subscript requires array or pointer type
I looked up past discussions but they are usually the error C2109 not pertaining to mex. Thank you in Advance.
This line is incorrect, B
and val
are pointers to double
, and therefore cannot be indexed twice, only once.
B[i][j] = val[i][j];
Think of the data in a MATLAB array as a 1D array, where the columns of the logical array are stacked. Given m
rows and n
columns, one can obtain the location in memory for the matrix element (i
,j
) with i + m*j
. Consequently, your copy operation should read:
B[i + m*j] = val[i + m*j];
However, the above is likely to lead to problems since n
is given by a second argument, and there is no guarantee that the input matrix has than many columns. You need to add an explicit test to verify that matrix
has at least n
columns, and that it is a double-valued matrix (if it is, for example, of type single
you'll be reading out of bounds as well, since mxGetPr
always returns a pointer to double
, not matter what the data in the array actually is.