Sparse Random Matrix with Eigen

1.6k views Asked by At

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.

3

There are 3 answers

1
Avi Ginsburg On BEST ANSWER

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

3
davidhigh On

Directly adapted from the Eigen Documentation, and not quite that concise:

std::default_random_engine gen;
std::uniform_real_distribution<double> dist(0.0,1.0);

int rows=100;
int cols=100;

std::vector<Eigen::Triplet<double> > tripletList;
for(int i=0;i<rows;++i)
    for(int j=0;j<cols;++j)
    {
       auto v_ij=dist(gen);                         //generate random number
       if(v_ij < 0.1)
       {
           tripletList.push_back(T(i,j,v_ij));      //if larger than treshold, insert it
       }
    }
SparseMatrixType mat(rows,cols);
mat.setFromTriplets(tripletList.begin(), tripletList.end());   //create the matrix

This requires C++11 and is untested.

0
Tong Zhou On

davidhigh's answer has O(rows*cols) complexity and can be impractical and take too long for large matrices. Here's an adapted version that has only O(nnz) complexity. p is the desired sparsity. You may adjust the range of valdis if the value in your matrix needs to be in other ranges.

typedef Eigen::SparseMatrix<double, Eigen::RowMajor> SpMat;

SpMat getRandomSpMat(size_t rows, size_t cols, double p) {
    typedef Eigen::Triplet<double> T;
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_real_distribution<> valdis(0, 1.0);
    std::uniform_int_distribution<> rowdis(0, rows-1);
    std::uniform_int_distribution<> coldis(0, cols-1);

    std::vector<Eigen::Triplet<double> > tripletList;
    size_t nnz = (size_t) (rows * (cols * p));
    std::set<size_t> nnz_pos;
    for (size_t i = 0; i < nnz; ++i) {
        auto r = rowdis(gen);
        auto c = coldis(gen);
        size_t pos = r * cols + c;
        while (nnz_pos.find(pos) != nnz_pos.end()) {
            r = rowdis(gen);
            c = coldis(gen);
            pos = r * cols + c;
        }

        nnz_pos.insert(pos);
        tripletList.push_back(T(r, c, valdis(gen)));
    }

    SpMat mat(rows,cols);
    mat.setFromTriplets(tripletList.begin(), tripletList.end());   //create the matrix
    return mat;
}