Is it possible to make a (sparse) matrix with the C++ Eigen library similar to this elegant python code I need to translate?
(np.random.rand(100,100) < 0.1) * np.random.rand(100,100)
e.g. a matrix filled with a certain proportion of random values.
davidhigh's answer addresses the sparse requirement of your question. However, I don't think that your python code actually produces a sparse matrix, but rather a dense matrix with mostly zeros. A similarly elegant version for Eigen can be
MatrixXd mat;
mat2 = (MatrixXd::Random(5,5).array() > 0.3).cast<double>() * MatrixXd::Random(5,5).array();
Note that this uses the standard C++ rand()
, so may not be sufficiently "random", depending on your needs. You can also replace MatrixXd
with MatrixXf
if you prefer float
s over double
s (change the cast<...>()
as well).