使用eigen删除零列或行

时间:2016-12-23 16:56:56

标签: c++ eigen

我想知道是否有更有效的方法来删除所有零元素的列或行。我确信有使用特征库中的函数,但我不知道如何。

现在我正在这样做,我想要使用while循环,以防多个行/列总和为零我不想超出范围限制或传递任何零行。

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

1 个答案:

答案 0 :(得分:2)

目前(Eigen 3.3),没有直接功能(虽然计划用于Eigen 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 << "\n\n";

// 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 << "\n\n";

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

使用Eigen 3.4可能会出现与此类似的情况(语法尚未最终):

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

这相当于Matlab / Octave:

res = A(:, any(A));
相关问题