How to remove a certain row or column while using Eigen Library c++

wholock picture wholock · Nov 8, 2012 · Viewed 16.2k times · Source

I am using Eigen library for my project. I am searching how to remove a certain row or column from the given matrix in Eigen. I am not successful.

MatrixXd A = X1 X2 X3 X4
             Y1 Y2 Y3 Y4
             Z1 Z2 Z3 Z4
             A1 A2 A3 A4
MatrixXd Atransform = X1 X2 X4
                      Y1 Y2 Y4
                      Z1 Z2 Z4
                      A1 A2 A4
enter code here

other than iterating through whole matrix or by using block operations on matrix A . Is there a method to do it simply.

Answer

Andrew picture Andrew · Jan 11, 2014

Using the block functions is a bit cleaner:

void removeRow(Eigen::MatrixXd& matrix, unsigned int rowToRemove)
{
    unsigned int numRows = matrix.rows()-1;
    unsigned int numCols = matrix.cols();

    if( rowToRemove < numRows )
        matrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.block(rowToRemove+1,0,numRows-rowToRemove,numCols);

    matrix.conservativeResize(numRows,numCols);
}

void removeColumn(Eigen::MatrixXd& matrix, unsigned int colToRemove)
{
    unsigned int numRows = matrix.rows();
    unsigned int numCols = matrix.cols()-1;

    if( colToRemove < numCols )
        matrix.block(0,colToRemove,numRows,numCols-colToRemove) = matrix.block(0,colToRemove+1,numRows,numCols-colToRemove);

    matrix.conservativeResize(numRows,numCols);
}