c++ - 使用特征删除零列或行

标签 c++ eigen

我想知道是否有更有效的方法来删除全为零元素的列或行。我确定使用了 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();
    }
}

最佳答案

目前(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));

关于c++ - 使用特征删除零列或行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41305178/

相关文章:

c++ - 在自定义类中定义 vector

c++ - 在递归函数中打印 C++ 中的累计和

c++ - 将 Matlab eig(A,B)(广义特征值/特征向量)重写为 C/C++

c++ - 使用 Eigen 的子矩阵和索引

将 Eigen::VectorXd 转换为 Eigen::MatrixXd 的 C++ lambda 函数

python - 为什么Python中的这段代码比C++快得多?

c++ - boost 和 Curl 不能一起工作

c++ - 基本的 cout/cin 问题

c++ - Eigen 将密集矩阵转换为稀疏矩阵

c++ - 使用 Eigen 库链接 Matlab 和 C++ 代码