Eigen matrix library filling a matrix with random float values in a given range

This might help:

#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main()
{
  double HI = 12345.67; // set HI and LO according to your problem.
  double LO = 879.01;
  double range= HI-LO;
  MatrixXd m = MatrixXd::Random(3,3); // 3x3 Matrix filled with random numbers between (-1,1)
  m = (m + MatrixXd::Constant(3,3,1.))*range/2.; // add 1 to the matrix to have values between 0 and 2; multiply with range/2
  m = (m + MatrixXd::Constant(3,3,LO)); //set LO as the lower bound (offset)
  cout << "m =\n" << m << endl;
}

Output:

m =
10513.2 10034.5  4722.9
5401.26 11332.6 9688.04
9858.54 3144.26 4064.16

The resulting matrix will contain pseudo-random elements of the type double in the range between LO and HI.


Combine the c++11 random number generators with a nullary expression from Eigen:

std::random_device rd;
std::mt19937 gen(rd());  //here you could also set a seed
std::uniform_real_distribution<double> dis(LO, HI);

//generate a 3x3 matrix expression
Eigen::MatrixXd::NullaryExpr random_matrix(3,3,[&](){return dis(gen);});

//store the random_number in a matrix M
Eigen::MatrixXd M = random_matrix;

Note that you get a new random number each time you call random_matrix(0,0). That's ok for matrix products, sum, and other operations which access the element once. If you need a random matrix that is used in more than one place, you can save it into an Eigen matrix M as shown in the last line.

Tags:

C++

Eigen

Eigen3