在做 matlab
转C++
代码时, 需要对 Eigen::MatrixXd
矩阵进行排序, 但未找到排序函数(也可能我找的不够仔细, 如果您找到了请留言告诉我!!), 所以自己写了一个对Eigen::MatrixX
模板类进行排序的函数, 希望对大家有帮助!
模板函数请放置到头文件中.
/**
* @brief 对矩阵 x 按行(或列)进行排序.
*
* @tparam _Scalar
* @param x 待排序的矩阵
* @param dim 0: 按行排序, 1: 按列排序
* @param ascend true: 升序, false: 降序
* @return Eigen::MatrixX<_Scalar> 排序后的矩阵
*/
template <typename _Scalar>
Eigen::MatrixX<_Scalar> sort(const Eigen::MatrixX<_Scalar> &x, int dim = 1, bool ascend = true)
{
Eigen::MatrixX<_Scalar> y(x);
auto pred_ascend = [](double a0, double a1){return a0 < a1;};
auto pred_descend = [](double a0, double a1){return a0 > a1;};
if(dim == 0)
{
if(ascend)
{
for(auto row: y.rowwise())
{
std::sort(row.begin(), row.end(), pred_ascend);
}
}
else
{
for(auto row: y.rowwise())
{
std::sort(row.begin(), row.end(), pred_descend);
}
}
}
else if(dim == 1 || dim == -1)
{
if(ascend)
{
for(auto col : y.colwise())
{
std::sort(col.begin(), col.end(), pred_ascend);
}
}
else
{
for(auto col : y.colwise())
{
std::sort(col.begin(), col.end(), pred_descend);
}
}
}
return y;
}
以下是从测试代码:
#include <iostream>
#include <Eigen/Dense>
#include "xxxx.h" // sort()模板函数定义在这里
int main(int, char**) {
Eigen::MatrixXd x(3,3);
x << 2, 9, 4,
7, 5, 3,
6, 1, 8;
std::cout << "x ascend sort by row: \n" << sort(x, 0) << std::endl;
std::cout << "x ascend sort by col: \n" << sort(x, 1) << std::endl;
std::cout << "x descend sort by col: \n" << sort(x, 1, false) << std::endl;
std::cout << "x descend sort by row: \n" << sort(x, 0, false) << std::endl;
}
测试结果如下: