Reputation: 527
I just played around with Eigen a bit and noticed that MatrixXf::Random(3,3) always returns the same matrices, first one is always this for example:
0.680375 0.59688 -0.329554
-0.211234 0.823295 0.536459
0.566198 -0.604897 -0.444451
Is that intended behaviour or am i just overseeing something really simple? (My experience with mathematic libraries is close to zero)
Code i used:
for(int i = 0; i < 5; i++) {
MatrixXf A = MatrixXf::Random(3, 3);
cout << A <<endl;
}
Upvotes: 13
Views: 10104
Reputation: 7810
How about this way?
#include<iostream>
#include<random>
#include <Eigen/Dense>
int main(){
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(0, 1);
Eigen::MatrixXf m = Eigen::MatrixXf::Zero(10,10).unaryExpr([&](float dummy){return dis(gen);});
cout<<"Uniform random matrix:\n"<<m<<endl;
cout<<"Mean: "<<m.mean()<<endl;
return 0;
}
Upvotes: 1
Reputation: 15468
Instead of srand
you can also use a nullary expression together with modern C++11 random number generation:
//see https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution
std::random_device rd;
std::mt19937 gen(rd()); //here you could set the seed, but std::random_device already does that
std::uniform_real_distribution<float> dis(-1.0, 1.0);
Eigen::MatrixXf A = Eigen::MatrixXf::NullaryExpr(3,3,[&](){return dis(gen);});
This also allows to use more complex distributions such as a normal distribution.
Upvotes: 28
Reputation: 41
@orian:
std::srand(unsigned seed) is not an Eigen function. The complete code should work like that:
std::srand((unsigned int) time(0));
for(int i = 0; i < 5; i++) {
MatrixXf A = MatrixXf::Random(3, 3);
cout << A <<endl;
}
Upvotes: 2
Reputation: 29205
Yes, that's the intended behaviour. Matrix::Random uses the random number generator of the standard library, so you can initialize the random number sequence with srand(unsigned int seed), for instance:
srand((unsigned int) time(0));
Upvotes: 23