MatrixXf::Random always returning same matrices

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));

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.


@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;
        }

Tags:

C++

Matrix

Eigen