Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eigen: how to remove an initialised coefficient from a sparse Matrix

Tags:

c++

eigen

I am writing a backward elimination algorithm. At each iteration I need to eliminate some coefficients from a column of a SparseMatrix and update the other non zero ones.

However, changing a reference to a coefficient to zero does not deallocate it, so the number of non zero coefficients is the same. How do I delete the reference? I tried with makeCompressed() to no avail and pruned is not known by the compiler.

Basic code below.

How can I solve this problem?

#include <Eigen/SparseCore>
void nukeit(){
  Eigen::SparseMatrix<double> A(4, 3);
  cout << "non zeros of empty: " << A.nonZeros() << "\n" << endl;

  A.insert(0, 0) = 1;
  A.insert(2, 1) = 5;
  cout <<  "non zeros are two: " << A.nonZeros() << "\n" << endl;

  A.coeffRef(0, 0) = 0;
  cout <<  "non zeros should be one but it's 2: " << A.nonZeros() << "\n" << endl;

  cout <<  "However the matrix has only one non zero element\n" << A << endl;
}

Output

non zeros of empty: 0

non zeros are two: 2

non zeros should be one but it's 2: 2

However the matrix has only one non zero element
0 0 0 
0 0 0 
0 5 0 
0 0 0 
like image 376
Marco Stamazza Avatar asked Aug 31 '25 21:08

Marco Stamazza


1 Answers

After setting some of the coefficients of the current column to zero, you can explicitly remove them by calling A.prune(0.0). See the respective doc.

However, be aware that this will trigger a costly memory copy of the remaining column entries. With sparse matrices, we usually never work in-place.

like image 119
ggael Avatar answered Sep 04 '25 04:09

ggael