Search code examples
c++sortingmatrixeigen

How to get largest n values in c++ vector (Eigen)?


I have a quite large Eigen matrix in c++, but now I want in each column only 6 values that are unequal 0. Herefore, I want to set all values to 0, except for the largest 6. I don't know how I can do that, can anyone help me?


Solution

  • //std
    #include <iostream>
    #include <vector>
    #include <numeric>
    //eigen
    #include <Eigen/Dense>
     
    using namespace std;
     
    int main()
    {
      Eigen::MatrixXf m(4,4);
      m <<  1, 2, 3, 4,
            5, 6, 7, 8,
            9,10,11,12,
           13,14,15,16;
           
      // Take the 2nd column
      auto col1 = m.col(1);
    
      // Generate a sequence of indices for each value in the column
      std::vector<size_t> idx(m.rows(), 0);
      std::iota(idx.begin(), idx.end(), 0);
    
      // Sort the indices according to their respective value
      std::sort(idx.begin(), idx.end(), [&col1](auto& lhv, auto& rhv){ return col1(lhv) < col1(rhv); });
    
      // Ignore the last 2 (so, the 2 biggest). Or 6 in your case.
      idx.resize(idx.size() - 2);
    
      // Set the rest to 0
      for(auto id: idx) {
          col1(id) = 0;
      }
    
      cout << m << endl; 
      // Output : 
      // 1  0  3  4
      // 5  0  7  8
      // 9  10 11 12
      // 13 14 15 16
    }