在 mex 函数中将特征复数矩阵返回到 matlab,无需额外复制

问题描述

这个问题展示了如何使用地图对象将双矩阵返回给 matlab。 Pass C++ Eigen matrix to Matlab mex output 以下适用于非复杂数据。

double *outputPtr;
plhs[0] = mxCreateDoubleMatrix((mwSize)n,(mwSize)m,mxREAL);
outputPtr = mxGetPr(plhs[0]);
Map<MatrixXd> output(outputPtr,n,m);

由于 matlab 单独存储矩阵的实数和复数元素而不是交错存储,因此我认为您不能直接映射到 MatrixXcd。这是我正在尝试的,但它不会写入 plhs[0] 处的数据。

double *outputReal,*outputImag;
plhs[0] = mxCreateDoubleMatrix((mwSize)n,mxCOMPLEX);
outputReal = mxGetPr(plhs[0]);
outputImag = mxGetPi(plhs[0]);
MatrixXcd outputMat(n,m);
outputMat.real() = Map<MatrixXd>(outputReal,m);
outputMat.imag() = Map<MatrixXd>(outputImag,m);

我认为问题在于它将这些映射中的数据复制到 outputMat 的实部和虚部。因此,这不仅会在初始化时进行不必要的复制,而且对以这种方式分配的矩阵的更改不会触及输出指针处的数据。

有没有办法初始化输出矩阵,使其实部和虚部数据存储在 mxGetPr(plhs[0]) 和 mxGetPi(plhs[0]) 中?

解决方法

感谢 Cris Luengo 为我指明了正确的方向。这就是我的工作。

plhs[0] = mxCreateDoubleMatrix((mwSize)n,(mwSize)m,mxCOMPLEX);
auto* Poutput = reinterpret_cast<complex<double>*>(mxGetComplexDoubles(plhs[0]));
Map<MatrixXcd> output(Poutput,n,m);

然后在编译时确保为 mex 提供 -R2018a 标志,该标志将为交错的复杂数据构建。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...