Pass C++ Eigen matrix to Matlab mex output

久未见 提交于 2019-12-12 16:37:29

问题


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.


回答1:


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... :)



来源:https://stackoverflow.com/questions/43163426/pass-c-eigen-matrix-to-matlab-mex-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!