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
?
So you're using Eigen. I'm not sure what matrix type you're using, but I'll go off the class
Eigen::MatrixXd
.What you need to do is:
The following code should do the trick, although you could implement it other ways.
I came up with even a better solution, which is a combination of
std::vector
,Egien::Map
andstd::shuffle
.This solution is memory efficient (since
Eigen::Map
doesn't copyesv
) and has the big advantage that if we want to permutees
several times (like in this case), then we just need to repeatstd::shuffle(std::begin(esv), std::end(esv), g);
Maybe I'm wrong, but this solution seems more elegant and efficient than the previous ones.
When
t
is close top
, Ryan's method need to generate much more thant
random numbers. To avoid this performance degrade, you could solve your original problemby the following steps
generate
t
uniformly distributed random numbersidx[t]
from [0, p-t+1)sort these numbers
idx[t]
idx[i]+i, i=0,...,t-1
are the resultThe code: