Eigen:如何制作矩阵的深层副本?

Kar*_*rus 10 c++ matrix eigen

使用 Eigen C++ 库,如何制作矩阵的深层复制?例如,如果我有:

Eigen::Matrix4f A;
Eigen::Matrix4f B = A;
Run Code Online (Sandbox Code Playgroud)

然后我修改A,它也会修改B。但我想B成为原作元素的复制品A。我怎样才能得到这个?

You*_*ang 11

auto初始化矩阵时不要使用,因为它会生成A = B浅表副本。auto还会造成其他意想不到的结果MatrixXd代替使用。

#include <iostream>
#include "Eigen/Dense"

using namespace Eigen;

typedef Matrix<double,Dynamic,Dynamic,RowMajor> MyMatrix;

int main()
{
    double a[] = {1,2,3,4};
    auto M = Map<MyMatrix>(a, 2, 2);
    auto G = M;
    MatrixXd g = M;
    G(0,0) = 0;
    std::cout << M << "\n" << std::endl;
    std::cout << G << "\n" << std::endl;
    std::cout << g << "\n" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

代码将输出:

0 2
3 4

0 2
3 4

1 2
3 4
Run Code Online (Sandbox Code Playgroud)