使用本特定删除零列或行

Removing zero columns or rows using eigen

本文关键字:零列 删除      更新时间:2023-10-16

我想知道是否有一种更有效的方法来删除所有元素的列或行。我敢肯定,在特征库中有功能,但我不知道如何。

现在,我正在这样做,以防万一有多个行/列的想法,我不想超过范围限制或传递任何零行。

void removeZeroRows() {
    int16_t index = 0;
    int16_t num_rows = rows();
    while (index < num_rows) {
        double sum = row(index).sum();
        // I use a better test if zero but use this for demonstration purposes 
        if (sum == 0.0) {
            removeRow(index);
        }
        else {
            index++;
        }
        num_rows = rows();
    }
}

当前(eigen 3.3),没有直接功能(尽管它计划针对特征3.4)。

同时,可以使用类似的东西(当然,rowcol可以互换,输出仅用于插图):

Eigen::MatrixXd A;
A.setRandom(4,4);
A.col(2).setZero();
// find non-zero columns:
Eigen::Matrix<bool, 1, Eigen::Dynamic> non_zeros = A.cast<bool>().colwise().any();
std::cout << "A:n" << A << "nnon_zeros:n" << non_zeros << "nn";
// allocate result matrix:
Eigen::MatrixXd res(A.rows(), non_zeros.count());
// fill result matrix:
Eigen::Index j=0;
for(Eigen::Index i=0; i<A.cols(); ++i)
{
    if(non_zeros(i))
        res.col(j++) = A.col(i);
}
std::cout << "res:n" << res << "nn";

通常,您应该避免在每次迭代时调整矩阵大小,但要尽快将其调整到最终尺寸。

使用eigen 3.4可能会有类似的东西(语法尚未最终):

Eigen::MatrixXd res = A("", A.cast<bool>().colwise().any());

这等效于matlab/octave:

res = A(:, any(A));