Using Eigen vectors in Matlab mex files

c++, eigen, matlab, mex

Solution

You are not allocating nothing in there. The line `double y_OUT[nrow] = {};` contains two errors. As described by the error messages.

- `nrow` is not `constexpr`. It cannot be evaluated at compile time.

- by the braces initializer you suggest the vector has `0` elements, it does not make sense either.

The proper syntax for dynamic allocation is: `double* y_OUT = new double[nrow];`. I think that is what you wanted. The syntax you used `double y_OUT[nrow]` is for used for static allocation, in other words where the size of array must be known at compile time.

Sidenotes: Of course you need to remember to free the memory you reserve. And the problem is totally unrelated to the topic IMO =)

Problem

I am trying to use the Eigen library for a c++ that I want to make into a mex file in Matlab. I broke the code down to its essentials below. I need to make a return vector of which the length corresponds to the number of rows from an input matrix. With the code below I get the follwing errors on compiling corresponding to the line: `double y_OUT[nrow] = {};` - error C2057: expected constant expression-error - error C2466: cannot allocate an array of constant size 0 I can't figure out why I cannot allocate the vector of length nrow. By uncommenting the specific line and by printing nrow i verified that it actually contains the right number. Does anyone can give any pointers (pun intended)? ``` void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *x_IN; int nrow,ncols; /* Check for proper number of arguments */ //... x_IN = mxGetPr(prhs[0]); nrow = (int)mxGetM(prhs[0]); ncols = (int)mxGetN(prhs[0]); double y_OUT[nrow] = {}; MatrixXd x=Map<MatrixXd>(x_IN,nrow,ncols); VectorXd Respons=VectorXd::Zero(nrow); Map<VectorXd>(y_OUT,nrow)=Respons.array(); return; } ```

Original source