Eigen::Matrix 有一个 setRandom() 方法,它将矩阵的所有系数设置为随机值。但是,在指定要使用的分布的同时,是否有一种内置的方法可以将所有矩阵系数设置为随机值。
有没有办法实现以下目标:
Eigen::Matrix3f myMatrix;
std::tr1::mt19937 gen;
std::tr1::uniform_int<int> dist(0,MT_MAX);
myMatrix.setRandom(dist(gen));
最佳答案
您可以使用 Boost 和 unaryExpr 做您想做的事。您传递给 unaryExpr 的函数需要接受一个您可以忽略的虚拟输入。
#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;
}
关于random - 根据任意分布设置 Eigen::Matrix 的系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11024820/