mardi 23 février 2021

How to sort and unique eigen matrix?

I am trying to sort a matrix and apply unique on in first and second column.

For an example:

3 98 31
3 99 31
2 98 31
2 99 31
2 98 31
3 91 31
3 98 31

After sorting and applying unique, I need

2 98 31
2 99 31
3 91 31
3 98 31
3 99 31

I tried to adopt [this solution][1] to my problem, but I could not able to make it work.

Here the code I tried:

void eigen_sort_unique_rows_by_head(Eigen::MatrixXi& A_nx3)
{
    std::vector<Eigen::VectorXi> vec;
    for (int64_t i = 0; i < A_nx3.rows(); ++i)
        vec.push_back(A_nx3.row(i));
 
    std::sort(vec.begin(), vec.end(), [](Eigen::VectorXi const& t1, Eigen::VectorXi const& t2){ return t1(0) < t2(0) ; } );
  //std::sort(vec.begin(), vec.end(), [](Eigen::VectorXi const& t1, Eigen::VectorXi const& t2){ return t1(1) < t2(1) ; } );
       //Here I am missing something, I tried with extra line of code it did not work
    
    auto it = std::unique(vec.begin(), vec.end());
    vec.resize(std::distance(vec.begin(),it));
    std::cout<<" vector size "<<vec.size()<<std::endl;

    A_nx3.resize(vec.size(),3);
    for (int64_t i = 0; i < vec.size(); ++i)
        A_nx3.row(i) = vec[i];
};

Can someone help me with this problem?

Thanks in advance. [1]: Sort Eigen matrix column values by ascending order of column 1 values

Aucun commentaire:

Enregistrer un commentaire