Eigen: How to make a deep copy of a matrix?
Asked Answered
R

2

13

Using the Eigen C++ library, how can I make a deep copy of a matrix? For example, if I have:

Eigen::Matrix4f A;
Eigen::Matrix4f B = A;

And then I modify A, it will also modify B. But I want B to be a copy of the elements of the original A. How can I get this?

Resplendence answered 24/3, 2015 at 11:43 Comment(4)
So, you want to imply that modifying A will modify B, but modifying B should not modify A?Syntactics
Can you write a minimal example. I don't think it should behave as you say docs mention it makes a copy, and making a matrix of references would seem quite nonsensical.Prominent
Are you sure you are not redefining the value of B = A after you change A?Mightily
This has to work: copy construction copies the memory. Please post the full code of your experiment.Remora
D
12

Do not use auto when initializing your matrices, as it will make A = B a shallow copy. auto will also cause other unexpected results. Use MatrixXd instead.

#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;
}

The codes would output:

0 2
3 4

0 2
3 4

1 2
3 4
Dorinedorion answered 7/1, 2020 at 7:1 Comment(0)
W
0

With your code

Eigen::Matrix4f A;
Eigen::Matrix4f B = A;

then B is a deep copy of A - see below:

int main(int argc, char* argv[]) {
  Eigen::Matrix4f A;

  A << 1,   2,  3,  4,
       5,   6,  7,  8,
       9,  10, 11, 12,
       13, 14, 15, 16;

  Eigen::Matrix4f B = A;
  std::cout << "------------------ original A:\n" << A << "\n";
  std::cout << "------------------ original B:\n" << B << "\n\n";

  // changing A(0, 3) does not change B:
  A(0, 3) = 40;
  std::cout << "------------------ A after the update:\n" << A << "\n";
  std::cout << "------------------ B remains what it was:\n" << B << "\n";


  return 0;
}
Wittenberg answered 24/3 at 15:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.