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

pincir picture pincir · Mar 6, 2016 · Viewed 9.3k times · Source

The setRandom function in the Eigen matrix library fills a given matrix with random numbers in the range [-1,1]. How can I extend this to generate numbers within any given range? I require floating point numbers and I am okay with pseudo-randomness.

I have tried doing the following:

B = LO + A.cast<double>().array()/(static_cast <double>(RAND_MAX)/(HI-LO));

Here A is the matrix in question and [LO,HI] is the range I am looking to fill it in. The problem is that the value of RAND_MAX for me is 2147483647 and this is messing up the entire calculation.

Any help is much appreciated.

Answer

RHertel picture RHertel · Mar 6, 2016

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.