2

How can I pass an Eigen Matrix as a Matlab output parameter?

I tried this from [EIGEN] How to get in and out data from Eigen matrix:

MatrixXd resultEigen;   // Eigen matrix with some result (non NULL!)
double *resultC;                // NULL pointer
Map<MatrixXd>( resultC, resultEigen.rows(), resultEigen.cols() ) = resultEigen;

But it lack information, how to pass the info in resultC to plhs[0] ? Also, when I run the code using this Map, Matlab closes.

Pedro77
  • 5,176
  • 7
  • 61
  • 91
  • You cannot get an `Eigen Matrix` into `Matlab`. What you can do is compute a lot using `Eigen` and use the underlying data to create an object, which `Matlab` understands and add it to `plhs`. – Jens Munk Apr 02 '17 at 00:41

1 Answers1

5

You need to first allocate the output MATLAB array, then create an Eigen::Map around it:

MatrixXd resultEigen; // Eigen matrix with some result (non NULL!)
mwSize rows = resultEigen.rows();
mwSize cols = resultEigen.cols();
plhs[0] = mxCreateDoubleMatrix(rows, cols, mxREAL); // Create MATLAB array of same size
Eigen::Map<Eigen::MatrixXd> map(mxGetPr(plhs[0]), rows, cols); // Map the array
map = resultEigen; // Copy

What this does is make an Eigen matrix (map) that has the MATLAB array (plhs[0]) as data. When you write into it, you are actually writing into the MATLAB array.

Note that you can create this map before doing your Eigen calculations, and use it instead of resultEigen, to avoid that final copy.

Note also that you can do exactly the same thing with the input arrays. Just make sure they are of class double (using mxIsDouble), or things might go horribly wrong... :)

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120