Eigen Sparse Matrix get Indices of Nonzero Elements
Asked Answered
D

3

7

I am using Eigen Sparse Matrices for the first time, and now I would like to know how to get the indices of the nonzero elements. I constructed my Sparse Matrix as follows:

Eigen::SparseMatrix<Eigen::ColMajor> Am(3,3);

and I can see some indices in VS by looking into the m_indices variable. But I can't access them. Can anyone please help me? For a Matrix like

( 1 0 1 
  0 1 1
  0 0 0 )

I would like the indices to be like (0,0), (0,2), (1,1), (1,2).

Is there any way to do it?

P.S. My matrices are way bigger than 3x3.

Dairyman answered 4/3, 2015 at 12:33 Comment(0)
H
9

The tutorial has code similar to this:

for (int k=0; k < A.outerSize(); ++k)
{
    for (SparseMatrix<int>::InnerIterator it(A,k); it; ++it)
    {
        std::cout << "(" << it.row() << ","; // row index
        std::cout << it.col() << ")\t"; // col index (here it is equal to k)
    }
}
Hinshelwood answered 9/3, 2015 at 6:24 Comment(2)
Would you have an idea why this gives me an error that the InnerIterator is private? ‘Eigen::SparseCompressedBase<Derived>::InnerIterator::InnerIterator(const Eigen::SparseMatrixBase<OtherDerived>&, Eigen::Index) [with T = Eigen::SparseMatrix<int, 1>; Derived = Eigen::SparseMatrix<int>; Eigen::Index = long int]’ is private within this context`?Immersed
Found out why it gave me that error: I did not specify that I wanted to use RowMajor. Using SparseMatrix<int, Eigen::RowMajor>::InnerIterator instead worked!Immersed
I
0
Eigen::SparseMatrix<int, Eigen::ColMajor> A(2,3);
for (int k=0; k < A.outerSize(); ++k)
{
    for (Eigen::SparseMatrix<int,Eigen::ColMajor>::InnerIterator it(A,k); it; ++it)
    {
        std::cout << "(" << it.row() << ","; // row index
        std::cout << it.col() << ")\t"; // col index (here it is equal to k)
    }
}
Insectivorous answered 4/12, 2019 at 8:16 Comment(1)
Hi and welcome to stackoverflow, and thank you for your answer. Rather than just posting a block of code, can you give a short explanation to what the issue is you solved and how you solved it? This will help people who find this question in the future to better understand the issue and how to deal with it.Ironworker
G
0

Using libigl's igl::find, you can extract the indices of non-zeros into Eigen vectors:

Eigen::VectorXi I,J;
Eigen::VectorXd V;
igl::find(Am,I,J,V);

In your example these will contain:

I: 0 1 0 1
J: 0 1 2 2
V: 1 1 1 1
Grandmamma answered 9/5, 2020 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.