Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an Eigen matrix to Triplet form C++

I think Eigen uses compressed methods to store sparse matrices. Is there any way that I can extract Triplet-format vectors of an Eigen sparse matrix in from of std::vectors?

Thanks.

More info (an example of triplet format) Triplet format of matrix :

A=
3 0 4 0
0 0 1 0
0 2 0 5
4 0 0 0

i = 1 1 2 3 3 4  // row
j = 1 3 3 2 4 1 // column
S = 3 4 1 2 5 4  // values
like image 331
Sina J Avatar asked Feb 23 '15 23:02

Sina J


1 Answers

The answer to the question, which is:

// Is there some method such as:

std::vector<Eigen::Triplet<double>> T = SparseMat.to_triplets();

// in Eigen?

Is no, there does not appear to be such a function.

Instead,

std::vector<Eigen::Triplet<double>> to_triplets(Eigen::SparseMatrix<double> & M){
    std::vector<Eigen::Triplet<double>> v;
    for(int i = 0; i < M.outerSize(); i++)
        for(typename Eigen::SparseMatrix<double>::InnerIterator it(M,i); it; ++it)
            v.emplace_back(it.row(),it.col(),it.value());
    return v;
}

auto t = to_triplets(SparseMat);

And if you want to do it faster, open it in an IDE, look around for pointers to the data arrays, and write a convoluted function that will have no effect on runtime, since the matrix is sparse, and copying is linear in terms of nonzero elements.

like image 97
Chris Avatar answered Sep 30 '22 10:09

Chris