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

亡梦爱人 提交于 2019-12-10 10:59:22

问题


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!


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/20986305/set-row-column-block-to-0-in-eigen-sparse-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!