I want to write a c++14/17 function to efficiently remove certain rows and columns in a (large) matrix. In my real application, the size of matrix can be (1000-by-1000). And I need to remove for example hundreds of inconsecutive columns and rows. Could you please show me how to implement this function?
#include <Eigen/Dense>
using Matrix = Eigen::MatrixXd;
using Vector = Eigen::Matrix<size_t, Eigen::Dynamic, 1>;
void remove_rs_and_cs_in_matrix(Matrix& m, Vector& rs, Vector& cs)
{
// m is a square matrix (n-by-n)
// rs stores the indices of the rows that should be deleted
// cs stores the indices of the columns that should be deleted.
}
int main()
{
Matrix m1 = Matrix::Constants(10, 10, 1.);
Vector rs1(4);
rs1 << 1, 3, 4, 7;
Vector cs2(3);
cs1 << 2, 8, 9;
remove_rs_and_cs_in_matrix(m1, rs1, cs1);
}
If instead of filling the indices of the row/columns you want to remove you fill the ones you want to keep, then with the head of the Eigen you can simply write:
Matrix M1;
std::vector<int> rk, ck; // or VectorXi
Matrix M2 = M1(rk,ck);