How to get the rows based on condition in eigen?

Viewed 272

I need to get the certain rows, when a element is a vector is one.

For an example:

std::vector<bool>index{};   //contains 6000 numbers of elements 0 and 1

Now I have a matrix mat of shape (6000,4)

How can I get the rows in a matrix mat, when the corresponding element is 1 in vector index.

mat = mat[index];
1 Answers

If I understand your question clearly, you may find good answer from this good reply:

Eigen3 select rows out based on column conditions

Using new feature (Eigen 3.4 or 3.3.90 development branch) and take the core code from the previous link:

#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; 
}

It uses the similar style of the Matlab:

MatrixXd mat_sel = mat(keep_rows, keep_cols); 

But the columns and rows that should be kept are stored in an

Eigen::VectorXi

or in a

std::vector<int>
Related