特征:具有t 1s的随机二进制向量 [英] Eigen: random binary vector with t 1s

查看:182
本文介绍了特征:具有t 1s的随机二进制向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算 K * es 其中 K Eigen 矩阵(维度 pxp )和 es px1 随机二进制向量与1s。



例如,如果 p = 5 t = 2 a es [1,0,1,0,0]' [0,0,1,1,0]'等等...



如何轻松生成

解决方案

我想出了一个更好的解决方案,它是 std :: vector Egien :: Map std :: shuffle

  std :: vector< int& esv(p,0); 
std :: fill_n(esv.begin(),t,1);
Eigen :: Map< Eigen :: VectorXi> es(esv.data(),esv.size());
std :: random_device rd;
std :: mt19937 g(rd());
std :: shuffle(std :: begin(esv),std :: end(esv),g);

这个解决方案是内存高效的(因为 Eigen :: Map 不复制 esv ),并且有很大的优势,如果我们要多次转换 es 像这样),那么我们只需要重复 std :: shuffle(std :: begin(esv),std :: end(esv),g); / p>

也许我错了,但是这个解决方案似乎比以前更加优雅和高效。


I want to compute K*es where K is an Eigen matrix (dimension pxp) and es is a px1 random binary vector with 1s.

For example if p=5 and t=2 a possible es is [1,0,1,0,0]' or [0,0,1,1,0]' and so on...

How do I easily generate es with Eigen?

解决方案

I came up with even a better solution, which is a combination of std::vector, Egien::Map and std::shuffle.

std::vector<int> esv(p,0);
std::fill_n(esv.begin(),t,1);
Eigen::Map<Eigen::VectorXi> es (esv.data(), esv.size());
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(std::begin(esv), std::end(esv), g);

This solution is memory efficient (since Eigen::Map doesn't copy esv) and has the big advantage that if we want to permute es several times (like in this case), then we just need to repeat std::shuffle(std::begin(esv), std::end(esv), g);

Maybe I'm wrong, but this solution seems more elegant and efficient than the previous ones.

这篇关于特征:具有t 1s的随机二进制向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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