8

How to set the new values to zero after resizing a matrix? It is really weird that after resizing the matrix, the new values are set to trash values instead of at least set to zero.

N = 0;
Eigen::MatrixXd CO;
CO.setZero(3+3*N, 3+3*N);
std::cout << CO << std::endl << std::endl;
Nt = 1;
CO.conservativeResize(3+3*Nt,3+3*Nt);
std::cout << CO << std::endl << std::endl;

The result

enter image description here

CroCo
  • 5,531
  • 9
  • 56
  • 88
  • 2
    It is a common practice to avoid initialization unless it was explicitly required. Otherwise you'd fill in the new values twice: first with 0, and then with the values you need. – Hope Feb 04 '19 at 10:44

3 Answers3

11

I've solved the problem by using conservativeResizeLike()

int Nt = 0;
Eigen::MatrixXd  CO;
CO.setOnes(3+3*Nt, 3+3*Nt);
std::cout << CO << std::endl << std::endl;
Nt = 1;
CO.conservativeResizeLike(Eigen::MatrixXd::Zero(3+3*Nt,3+3*Nt));
std::cout << CO << std::endl << std::endl;

The result

enter image description here

Also, I found out you can set them as ones Eigen::MatrixXd::Ones(3+3*Nt,3+3*Nt) or identity Eigen::MatrixXd::Identity(3+3*Nt,3+3*Nt)

For Identity

enter image description here

CroCo
  • 5,531
  • 9
  • 56
  • 88
3

Those values are not so much "trash" values as they are "uninitialized memory" values. It is your responsibility to set them to whatever values make sense to you. It should not be difficult to iterate over the new values and zero them if you wish.

Logicrat
  • 4,438
  • 16
  • 22
  • 2
    I'm sorry but this is not a solution. I can iterate over the new values but it seems odd that there is no default values at least with zeros. – CroCo Aug 14 '14 at 21:19
  • 1
    @CroCo If you want the value to be set "automatically" when you resize a matrix, you do have the option of creating a derivative class of Eigen::MatrixXd that would do that (unless it is declared with the `final` keyword). – Logicrat Aug 14 '14 at 21:34
  • 1
    @CroCo Well, the documentaton here: http://eigen.tuxfamily.org/dox/classEigen_1_1PlainObjectBase.html says this: `Matrices are resized relative to the top-left element. In case values need to be appended to the matrix *they will be uninitialized*.` – PaulMcKenzie Aug 14 '14 at 21:38
0

I am not sure which version of Eigen you are working with. But as of today, Eigen has a setZero() function which sets all coefficients in this expression to zero.

Here is the documentation: Derived & Eigen::DenseBase< Derived >::setZero ( )

jackxujh
  • 983
  • 10
  • 31