Eigen::Matrix 排序

在做 matlabC++代码时, 需要对 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;
}

测试结果如下:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

falwat

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值