【问题标题】:How to get the rows based on condition in eigen?如何根据特征中的条件获取行?
【发布时间】: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];

【问题讨论】:

    标签: c++ c++17 eigen


    【解决方案1】:

    如果我清楚地理解了您的问题,您可能会从这个好的回复中找到好的答案:

    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>
    

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • 根据参考链接添加核心代码。
    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    相关资源
    最近更新 更多