Question

I need some number generator for matrix in c++, but with specific range. For example, I need random matrix in range <-1,1> or <0,1>. So I need some function, which parameters are specific intervals.

Thanks

Was it helpful?

Solution

If your compiler supports C++11, you could iterate over the elements of your matrix and randomly initialize them with numbers in the range [a,b] like below:

#include <iostream>
#include <chrono>
#include <random>

void fillMatrixRnd(YourMatrix &M, double const a, double const b)
{
  // construct a trivial random generator engine from a time-based seed:
  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
  std::default_random_engine generator (seed);
  std::uniform_real_distribution<double> distribution (a, b);
  for(auto e : M) e = distribution(generator); // Change here according to your needs
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top