echo
echo

Reputation: 799

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

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!

Upvotes: 2

Views: 5283

Answers (3)

Rockcat
Rockcat

Reputation: 3250

For beginners, the simplest way set to zero a row/column/block is just to multiply it by 0.0.

Eigen::SparseMatrix<float, Eigen::RowMajor> A;

A = MatrixXf::Random(8,8).sparseView(); //Initialize to random values

A.block(1, 1, 2, 2) *= 0; //Set a block to 0
A.row(1) *= 0;            //Set a row to 0
A.col(1) *= 0;            //Set a column to 0

std::cout << A << "\n";

Using prune() to set a block to zero can be faster if the density of your sparse matrix is high, but for most cases *= 0is quite fast and you don't have to rewrite your code depending of RowMajor/ColMajor ordering.

If you are really interested in free memory after setting the row/col to 0, just add a A.prune(0,0) after you have finished editing the matrix.

Upvotes: 2

joanvallve
joanvallve

Reputation: 11

Eigen's Tutorial for sparse matrices (Tutorial Sparse: block operations) explain that for ColumnMajor (resp. RowMajor) sparse matrices, the column (resp. row) sub-matrix operators have write-access.

So, for example, to set to zero the 2nd, 3rd and 4th rows of a rowmajor sparse matrix you could do: Eigen::SparseMatrix<float, Eigen::RowMajor> A; A = MatrixXf::Random(5,5).sparseView(); A.middleRows(1,3) = Eigen::SparseMatrix<float,Eigen::RowMajor>(3,A.cols());

And leave prune() for setting to zero columns of row major matrices and vicevesa.

Upvotes: 1

ggael
ggael

Reputation: 29265

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";
}

Upvotes: 6

Related Questions