【发布时间】:2021-05-25 12:00:47
【问题描述】:
当一个元素是一个向量时,我需要获取某些行。
举个例子:
std::vector<bool>index{}; //contains 6000 numbers of elements 0 and 1
现在我有一个形状为 (6000,4) 的矩阵垫
当向量索引中的对应元素为 1 时,如何获取矩阵 mat 中的行。
mat = mat[index];
【问题讨论】:
当一个元素是一个向量时,我需要获取某些行。
举个例子:
std::vector<bool>index{}; //contains 6000 numbers of elements 0 and 1
现在我有一个形状为 (6000,4) 的矩阵垫
当向量索引中的对应元素为 1 时,如何获取矩阵 mat 中的行。
mat = mat[index];
【问题讨论】:
如果我清楚地理解了您的问题,您可能会从这个好的回复中找到好的答案:
Eigen3 select rows out based on column conditions
使用新功能(Eigen 3.4 或 3.3.90 开发分支)并从上一个链接中获取核心代码:
#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;
}
它使用了类似Matlab的风格:
MatrixXd mat_sel = mat(keep_rows, keep_cols);
但是应该保留的列和行存储在一个
Eigen::VectorXi
或在一个
std::vector<int>
【讨论】: