我想知道是否有更有效的方法来删除全为零元素的列或行。我确定使用了 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)。
同时可以这样使用(当然row
和col
可以互换,输出只是为了说明):
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/