9

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?

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • So, you want to imply that modifying `A` will modify `B`, but modifying `B` should not modify `A`? – shauryachats Mar 24 '15 at 11:50
  • Can you write a minimal example. I don't think it should behave as you say [docs](http://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html) mention it makes a copy, and making a matrix of references would seem quite nonsensical. – luk32 Mar 24 '15 at 11:57
  • Are you sure you are not redefining the value of B = A *after* you change A? – Aphire Mar 24 '15 at 12:03
  • This has to work: copy construction copies the memory. Please post the full code of your experiment. – Roman Shapovalov Nov 15 '16 at 16:46

1 Answers1

7

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
Youwei Liang
  • 361
  • 4
  • 9