Home Eigen 删除行或列
Post
Cancel

Eigen 删除行或列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Delete one row or one column from a matrix
// dim: 1 -> row; 2 -> col
template <typename Derived>
void DeleteRowOrCol(Eigen::PlainObjectBase<Derived> &matrix, const unsigned index, const int dim)
{
    unsigned rows = matrix.rows();
    unsigned cols = matrix.cols();
    if (dim == 1)
    {
        if (index < rows)
        {
            rows -= 1;
            matrix.block(index, 0, rows - index, cols) = matrix.bottomRows(rows - index);
        }
    }
    if (dim == 2)
    {
        if (index < cols)
        {
            cols -= 1;
            matrix.block(0, index, rows, cols - index) = matrix.rightCols(cols - index);
        }
    }
    matrix.conservativeResize(rows, cols);
}

// Delete multi rows or multi columns from a matrix
// dim: 1 -> row; 2 -> col
template <typename Derived>
void DeleteRowsOrCols(
    Eigen::PlainObjectBase<Derived> &matrix, const std::vector<unsigned> &indexes, const int dim)
{
    if (dim != 1 || dim != 2) return;   // guard clauses
    unsigned rows = matrix.rows();
    unsigned cols = matrix.cols();
    for (const unsigned index : indexes)
    {
        int delta = rows - matrix.rows() + cols - matrix.cols();
        DeleteRowOrCol(matrix, index - delta, dim);
    }
}
This post is licensed under CC BY 4.0 by the author.