How to remove duplicate rows in matrix in eigen?

Viewed 384

I am trying to apply a uniqueness to MatrixXi in eigen. But I didn't find any workaround or api in eigen library.

My goal is :

MatrixXi mat = {{1,2,3},{2,3,1},{4,5,6},{1,2,3},{1,3,2},{4,3,5},{4,5,6}}

After apply uniqueness, I need

auto mat_unique = {{1,2,3},{1,3,2},{2,3,1},{4,3,5},{4,5,6}}

I need to apply uniqueness for bigger matrix.

Is there any workaround or APi in eigen?

Thanks in advance

1 Answers

I have found solution to my problem. Here is this

But the solution is only for sorting, not for removing duplicates. So one needs to add one more line of code in the middle.

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

    auto it = std::unique(vec.begin(), vec.end());
    vec.resize(std::distance(vec.begin(),it));

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