【问题标题】:Return eigen complex matrix to matlab in mex function without extra copy在 mex 函数中将特征复数矩阵返回到 matlab,无需额外复制
【发布时间】:2021-04-14 17:24:29
【问题描述】:

这个问题展示了如何使用地图对象将双矩阵返回给 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, (mwSize)m, mxCOMPLEX);
outputReal = mxGetPr(plhs[0]);
outputImag = mxGetPi(plhs[0]);
MatrixXcd outputMat(n,m);
outputMat.real() = Map<MatrixXd>(outputReal,n,m);
outputMat.imag() = Map<MatrixXd>(outputImag,n,m);

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

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

【问题讨论】:

  • Eigen 目前仅支持复杂值的交错存储,因此您需要设置两个单独的输出 Map。
  • 由于 MATLAB R2018a 复数是交错存储的。您需要使用 -R2018a 选项编译 MEX 文件,否则复杂数据将被复制到单独的实数和虚数数组中以实现向后兼容性。 mathworks.com/help/matlab/matlab_external/…

标签: c++ matlab eigen mex eigen3


【解决方案1】:

感谢 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 标志,该标志将为交错的复杂数据构建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多