gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:06:36 25 4
gpt4 key购买 nike

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

关于c++ - 如何将复数矩阵从 Matlab R2018a 转移到 Eigen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50054487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com