drbombe
drbombe

Reputation: 639

Eigen C++: How can I fixed the values after a random matrix initialization?

It seems that in Eigen package, the coefficients keep changing after a random matrix initialization. Some illustration codes and output are listed below. We expect that X.transpose() is the transpose of the first X. But it is a transpose of another random matrix!

How can I fixed the those values after random matrix initialization?

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


using namespace Eigen;
using namespace std;
int main(){
  auto X = MatrixXi::Random(2,2);
  cout << X << endl;
  cout << "---------" << endl;
  cout << X.transpose() << endl;
  cout << "---------" << endl;
  cout << X << endl;
  cout << "---------" << endl;
  return 0;
}

Output:

-1073725017   548908249
 -791266575   -88798166
---------
  70367106 -603530552
-972714280  384109054
---------
 385036099 -250177384
 933495885   41696341
---------

Upvotes: 0

Views: 174

Answers (1)

Avi Ginsburg
Avi Ginsburg

Reputation: 10596

Don't use auto with Eigen unless you know what you're doing. The result of auto X = MatrixXi::Random(2,2); is an expression that creates a random matrix when evaluated. It's getting evaluated again and again at each call of cout. Instead use MatrixXi X = MatrixXi::Random(2,2);.

Upvotes: 6

Related Questions