如何将复数矩阵从 Matlab R2018a 转移到 Eigen

How can I transfer a complex matrix from Matlab R2018a to Eigen

我目前正在将矩阵的实部和虚部分别从 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类型。

如果我理解正确,mxComplexDoublestd::complex<double> 具有相同的布局,因此您应该能够简单地转换:

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

参考:

In the -R2018a API, the mxGetElementSize function returns sizeof(std::complex<T>) for a complex mxArray with data type T. This value is twice the value returned by the function in the -R2017b API.

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