Eigen3根据列条件选择行 [英] Eigen3 select rows out based on column conditions

查看:683
本文介绍了Eigen3根据列条件选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在本征中有一个二维的矩阵,例如:

I have a matrix in eigen which is 2 dimensions, such as:

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
.....

我要选择所有行(或得到它的

I want select all rows (or get it's row index out) when the last column value bigger than 0.3.

我知道我可以通过迭代所有行并判断最后一个元素来做到这一点,但是我可能有10000行,为此,迭代将非常缓慢。

I know I can do this by iteration all rows and judge the last element, but I have maybe 10000 rows, to do this, iteration will be very slow.

还有更好的方法吗?

推荐答案

通过将最后一列中所有元素的比较结果存储到一个布尔数组中,可以在一行中选择相关行。 VectorXi。

The selection of the relevant rows can be done in a single line, by storing the result of the comparison of all the elements in the last column into a boolean array, which can be cast into a VectorXi.

VectorXi is_selected = (mat.col(last_col).array() > 0.3).cast<int>();

然后可以使用此信息准备仅包含选定行的新矩阵。使用此方法的完整代码如下所示。

This information can then be used to prepare a new matrix which contains only the selected rows. An entire code using this method is shown below.

#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构造函数的新重载,允许直接给定矩阵的子集。

The development branch of Eigen provides a new overload of the MatrixX constructor that allows for the direct subsetting of a given matrix.

MatrixXd mat_sel = mat(keep_rows, keep_cols); 

应保留的列和行存储在 Eigen ::中VectorXi std :: vector< int>

The columns and rows that should be kept are stored in an Eigen::VectorXi or in a 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

这篇关于Eigen3根据列条件选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆