如何去除 Eigen3 矩阵中某些不连续的行和列?

How to remove certain inconsecutive rows and columns in Eigen3 matrix?

我想编写一个 c++14/17 函数来有效地删除(大)矩阵中的某些行和列。在我的实际应用中,矩阵的大小可以是(1000×1000)。我需要删除例如数百个不连续的列和行。你能告诉我如何实现这个功能吗?

#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);
}

如果不是填充要删除的 row/columns 的索引,而是填充要保留的索引,那么使用 Eigen 的头部,您可以简单地写:

Matrix M1;
std::vector<int> rk, ck; // or VectorXi
Matrix M2 = M1(rk,ck);