根据任意分布设置Eigen :: Matrix的系数 [英] Set coefficients of an Eigen::Matrix according an arbitrary distribution

查看:78
本文介绍了根据任意分布设置Eigen :: Matrix的系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Eigen :: Matrix具有setRandom()方法,该方法会将矩阵的所有系数设置为随机值.但是,有一种内置的方式可以将所有矩阵系数设置为随机值,同时指定要使用的分布.

Eigen::Matrix has a setRandom() method which will set all coefficients of the matrix to random values. However, is there a built in way to set all the matrix coefficients to random values while specifying the distribution to use.

有没有办法实现以下目标:

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));

推荐答案

您可以使用Boost和unaryExpr进行所需的操作.传递给unaryExpr的函数需要接受一个虚拟输入,您可以忽略该输入.

You can do what you want using Boost and unaryExpr. The function you pass to unaryExpr needs to accept a dummy input which you can just 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;
}

这篇关于根据任意分布设置Eigen :: Matrix的系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆