Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set row/column/block to 0 in Eigen sparse matrix?

Tags:

eigen

I see with new Eigen 3.2, you can get row, column or even block from a sparse matrix, is there a way to set any of these to 0?

Eigen::SparseMatrix<float, Eigen::RowMajor> A( 5, 5 );
    A.block(1, 1, 2, 2) = 0; // won't work
    A.row(1) = 0; // won't work
    A.col(1) = 0; // won't work

Thanks!

like image 915
echo Avatar asked Mar 10 '26 14:03

echo


1 Answers

For 5x5 matrices, it is overkill to use a sparse matrix. Better use a MatrixXd, or even a Matrix<float,5,5>. In this case you can set a row to zero with A.row(1).setZero(). Sparse matrices are worth it for matrices of size about 1000x1000 and greater.

Anyway, the best to suppress multiple columns and rows of a sparse matrix at once is to use the prune method. Here is an example removing the second row and third column:

#include <Eigen/Sparse>
#include <iostream>

using namespace Eigen;

int main()
{
  Eigen::SparseMatrix<float, Eigen::RowMajor> A;
  A = MatrixXf::Random(5,5).sparseView();
  A.prune([](int i, int j, float) { return i!=1 && j!=2; });
  std::cout << A << "\n";
}
like image 104
ggael Avatar answered Mar 13 '26 10:03

ggael