Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a specific (row,col) index in an C++ Eigen sparse matrix?

I'm working in C++ with a sparse matrix in Eigen. I would like to read the data stored in a specific row and column index just like I would with a regular eigen matrix.

std::vector<Eigen::Triplet<double>> tripletList;

// TODO: populate triplet list with non-zero entries of matrix

Eigen::SparseMatrix<double> matrix(nRows, nCols);
matrix.setFromTriplets(tripletList.begin(), tripletList.end());

// TODO:  set iRow and iCol to be valid indices.

// How to read the value at a specific row and column index?
// double value = matrix(iRow, iCol);  // Compiler error

How do I go about performing this type of indexing operation?

like image 584
MattKelly Avatar asked Feb 21 '17 19:02

MattKelly


2 Answers

Try coeff:

double value = matrix.coeff(iRow, iCol);

If you want a non-const version use coeffRef instead. Note that when using coeffRef if the element doesn't exist, it will be inserted.

like image 134
Avi Ginsburg Avatar answered Oct 23 '22 14:10

Avi Ginsburg


This Code work for me

for (int i=0; i<matrix.rows(); ++i){
     for(int j=0; i<matrix.cols(); ++j)
        cout << " i,j=" << i << "," 
             << j << " value=" 
             << matrix.coeff(i,j) 
             << std::endl;
}

like image 39
Hamza Siraj Avatar answered Oct 23 '22 14:10

Hamza Siraj