conservativeResize() with zero values for the new values
Asked Answered
D

3

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

Deglutinate answered 14/8, 2014 at 21:12 Comment(1)
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.Flatter
D
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

Deglutinate answered 14/8, 2014 at 21:55 Comment(0)
A
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.

Anzac answered 14/8, 2014 at 21:15 Comment(3)
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.Deglutinate
@Deglutinate 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).Anzac
@Deglutinate Well, the documentaton here: 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*.Infant
A
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 ( )

Allyn answered 21/11, 2019 at 4:10 Comment(2)
I've asked it 5 years ago. They may fix it but thanks for the update.Deglutinate
yeah, it is nice to have a simple initializer filling zeros.Allyn

© 2022 - 2024 — McMap. All rights reserved.