Search code examples
pythonc++sparse-matrixeigen

Sparse Random Matrix with Eigen


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.


Solution

  • 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 floats over doubles (change the cast<...>() as well).