特征 3 根据列条件选择出行
Eigen3 select rows out based on column conditions
我有一个特征矩阵,它是 2 维的,例如:
122 443 544 456 0.9
324 435 5465 645 0.8
32 434 545 546 0.778
435 546 6565 656 0.6878
546 6565 656 3453 54 0.7788
5456 546 545 6565 3434 0.244
435 5456 656 656 6565 0.445
.....
我想在最后一列值大于 0.3 时选择所有行(或将其行索引取出(。
我知道我可以通过迭代所有行并判断最后一个元素来做到这一点,但我可能有 10000 行,要做到这一点,迭代会非常慢。
有没有更好的方法可以做到这一点?
相关行的选择可以在一行中完成,方法是将最后一列中所有元素的比较结果存储到布尔数组中,该数组可以转换为 VectorXi。
VectorXi is_selected = (mat.col(last_col).array() > 0.3).cast<int>();
然后,此信息可用于准备仅包含所选行的新矩阵。使用此方法的整个代码如下所示。
#include <Eigen/Dense>
#include <iostream>
using namespace Eigen;
int main() {
const int nr = 10;
const int nc = 5;
MatrixXd mat = MatrixXd::Random(nr,nc);
std::cout << "original:n" << mat << std::endl;
int last_col = mat.cols() - 1;
VectorXi is_selected = (mat.col(last_col).array() > 0.3).cast<int>();
MatrixXd mat_sel(is_selected.sum(), mat.cols());
int rownew = 0;
for (int i = 0; i < mat.rows(); ++i) {
if (is_selected[i]) {
mat_sel.row(rownew) = mat.row(i);
rownew++;
}
}
std::cout << "selected:n" << mat_sel << std::endl;
}
演示:https://godbolt.org/z/f0_fC0
编辑:使用新功能(特征3.4或3.3.90开发分支(
Eigen 的开发分支提供了 MatrixX 构造函数的新重载,允许对给定矩阵进行直接子集化。
MatrixXd mat_sel = mat(keep_rows, keep_cols);
应保留的列和行存储在Eigen::VectorXi
或std::vector<int>
中:
#include <Eigen/Dense>
#include <iostream>
#include <vector>
using namespace Eigen;
int main() {
MatrixXd mat = MatrixXd::Random(10,5);
std::cout << "original:n" << mat << std::endl;
std::vector<int> keep_rows;
for (int i = 0; i < mat.rows(); ++i) {
if (mat(i,mat.cols() - 1) > 0.3) {
keep_rows.push_back(i);
}
}
VectorXi keep_cols = VectorXi::LinSpaced(mat.cols(), 0, mat.cols());
MatrixXd mat_sel = mat(keep_rows, keep_cols);
std::cout << "selected:n" << mat_sel << std::endl;
}
演示:https://godbolt.org/z/Ag7g7f
您可以尝试使用列而不是行,并将最后一列与 0.3 的向量 [n x 1] 进行比较
相关文章:
- 有条件地选择带有 decltype() 和三元运算符的类型
- 特征 3 根据列条件选择出行
- 用于根据条件选择编译时类型的可变参数模板
- 使用 std::条件根据模板参数选择成员类型
- 除了使用 #define 进行条件编译之外,还有其他选择吗?
- 根条件分支选择
- 最佳无分支有条件选择两个SSE2填充双打
- 内联函数选择条件
- 当列中的属性与eigen,c 中的给定条件匹配时,仅选择这些行froom a矩阵
- 如何根据条件选择结构
- 根据编译时条件在类型之间选择类型的惯用方法
- 如何使用std ::有条件地选择一个免费功能
- 根据条件在3种不同的地图中进行选择
- 在什么条件下,数据库在从 cpp 执行选择查询时不会关闭游标
- C++:如何根据条件选择构造函数
- 使用条件语句在运行时选择不同的模板化矩阵类
- C 循环多项选择条件
- 根据 c-tor 的特定条件选择要初始化的变量
- 没有选择语句的C++条件
- 根据条件选择结构