Set the coefficients of the matrix Eigen :: Matrix according to an arbitrary distribution

Eigen :: Matrix has a setRandom () method that sets all matrix coefficients to random values. However, there is a built-in way to set all matrix coefficients to random values ​​when specifying the distribution used.

Is there a way to achieve something like the following:

Eigen::Matrix3f myMatrix; std::tr1::mt19937 gen; std::tr1::uniform_int<int> dist(0,MT_MAX); myMatrix.setRandom(dist(gen)); 
+4
source share
2 answers

You can do what you want using Boost and unaryExpr. The function you pass to unaryExpr should accept dummy input, which you can simply ignore.

 #include <boost/random.hpp> #include <boost/random/normal_distribution.hpp> #include <iostream> #include <Eigen/Dense> using namespace std; using namespace boost; using namespace Eigen; double sample(double dummy) { static mt19937 rng; static normal_distribution<> nd(3.0,1.0); return nd(rng); } int main() { MatrixXd m =MatrixXd::Zero(2,3).unaryExpr(ptr_fun(sample)); cout << m << endl; return 0; } 
+3
source

Besides the uniform distribution, I do not know other types of distribution that can be used directly on the matrix. What you can do is map the uniform distribution provided by Eigen directly into your custom distribution (if the mapping exists).

Suppose your distribution is a sigmoid. You can map the uniform distribution into a sigmoid distribution using the function y = a / (b + c exp (x)).

By temporarily converting your matrix to an array, you can control over the elements in all the values ​​of your matrix:

 Matrix3f uniformM; uniformM.setRandom(); Matrix3f sigmoidM; sigmoidM.array() = a * ((0.5*uniformM+0.5).array().exp() * c + b).inv(); 
+1
source

All Articles