使用特征消除零列或行 [英] Removing zero columns or rows using eigen
问题描述
我想知道是否有一种更有效的方法来删除全部为零元素的列或行。我确定本征库中正在使用这些函数,但我不知道该怎么做。
I was wondering if there is a more efficient way to remove columns or rows that are all zero elements. I am sure there is using the functions in the eigen library but I do not know how.
现在,我正在这样做,并带有while循环的想法在有多个行/列加起来为零的情况下使用,我不想超出范围限制或不传递任何零行。
Right now I am doing it like so, with the idea of the while loop being used in case there are multiple rows/columns that sum to zero I dont want to exceed range limits or pass any zero rows.
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)。
Currently (Eigen 3.3), there is no direct functionality for this (though it is planned for Eigen 3.4).
同时,可以使用类似的功能(当然,行
和 col
可以互换,并且输出仅用于说明):
Meanwhile can use something like this (of course, row
and col
can be interchanged, and output is just for illustration):
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";
通常,您应避免在每次迭代时调整矩阵大小,但应尽快将其调整为最终大小
Generally, you should avoid resizing a matrix at every iteration, but resize it to the final size as soon as possible.
使用Eigen 3.4可能会出现类似的情况(语法尚未最终确定):
With Eigen 3.4 something similar to this will be possible (syntax is not final yet):
Eigen::MatrixXd res = A("", A.cast<bool>().colwise().any());
与Matlab / Octave等效:
Which would be equivalent to Matlab/Octave:
res = A(:, any(A));
这篇关于使用特征消除零列或行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!