如何将复杂矩阵从Matlab R2018a传输到Eigen

时间:2018-04-27 02:48:28

标签: c++ matlab eigen mex

我目前正在将矩阵的实部和虚部分别从Matlab导入C ++。然后我还将实部和虚部分别映射到Eigen。我还执行计算并分别映射最终结果,如下所示:

//import real and imaginary parts from matlab 
mwSize     M = mxGetM (prhs[1]);
mwSize     N = mxGetN (prhs[1]);
double  * PR = mxGetPr (prhs[1]);
double  * PI = mxGetPi (prhs[1]);

//map real and imaginary parts to Eigen
Map<Matrix<double,Dynamic,Dynamic,ColMajor> > Br (PR, M, N );
Map<Matrix<double,Dynamic,Dynamic,ColMajor> > Bi (PI, M, N );

//map real and imaginary parts of result 
plhs[0] = mxCreateDoubleMatrix(M, N, mxCOMPLEX);
Map<Matrix<double,Dynamic,Dynamic,ColMajor> > resultr (mxGetPr(plhs[0]), M, N);
Map<Matrix<double,Dynamic,Dynamic,ColMajor> > resulti (mxGetPi(plhs[0]), M, N);

//calculate real and imaginary parts of A*B separately
resultr=A*Br;
resulti=A*Bi;

但是,从R2018a开始,Matlab allows importing the real and imaginary parts together

我该怎么做?我尝试了以下方法:

//import complex matrix from matlab 
mwSize     N = mxGetN (prhs[1]);
mxComplexDouble  * PR = mxGetComplexDoubles (prhs[1]);

//map complex matrix to eigen
Map<Matrix<mxComplexDouble,Dynamic,Dynamic,ColMajor> > B (PR, M, N );

//map complex result
plhs[0] = mxCreateDoubleMatrix(M, N, mxCOMPLEX);
Map<Matrix<mxComplexDouble,Dynamic,Dynamic,ColMajor> > result (mxGetDoubles(plhs[0]), M, N);

//calculate real and imaginary parts together
result=A*B;

但它没有编译,因为Eigen不喜欢mxComplexDouble类型。

1 个答案:

答案 0 :(得分:2)

如果我理解正确,mxComplexDouble的布局与std::complex<double>相同,那么您应该能够简单地投射:

auto* PR = reinterpret_cast<std::complex<double>*>(mxGetComplexDoubles(prhs[1]));

<强>参考:

  

-R2018a API中,mxGetElementSize函数会为数据类型为sizeof(std::complex<T>)的复杂mxArray返回T。此值是-R2017b API中函数返回的值的两倍。

从MATLAB文档页面"Upgrade MEX Files to Use Interleaved Complex API"