Eigen库实现矩阵的按行和按列循环移位

        在处理矩阵运算时,我们有时需要实现矩阵的按行和按列循环位移。为此,我们可以使用Eigen库,这是一个用于线性代数、矩阵和向量运算、数值计算以及几何变换的C++库。在这里,我将展示如何使用Eigen库实现矩阵的按行和按列循环位移。

        下面是一个定义了循环位移函数的示例代码。这个函数名为circshift_mat,接受一个MatrixXd类型的输入矩阵、一个整数shift表示位移量,以及一个整数axis表示要沿哪个轴进行位移(0表示行,1表示列)。

#include <Eigen/Dense>

// 定义一个循环位移函数,适用于MatrixXd矩阵,0为行,1为列

MatrixXd circshift_mat(const MatrixXd& input, int shift, int axis)
{
    MatrixXd shifted = input;
    int rows = input.rows();
    int cols = input.cols();  

    if (axis == 0) { // 沿行进行位移
        if (shift >= 0) {
            shifted.block(shift, 0, rows - shift, cols) = input.block(0, 0, rows - shift, cols);
            shifted.block(0, 0, shift, cols) = input.block(rows - shift, 0, shift, cols);
        }
        else {
            shift = -shift;
            shifted.block(0, 0, rows - shift, cols) = input.block(shift, 0, rows - shift, cols);
            shifted.block(rows - shift, 0, shift, cols) = input.block(0, 0, shift, cols);
        }
    }
    else if (axis == 1) { // 沿列进行位移
        if (shift >= 0) {
            shifted.block(0, shift, rows, cols - shift) = input.block(0, 0, rows, cols - shift);
            shifted.block(0, 0, rows, shift) = input.block(0, cols - shift, rows, shift);
        }
        else {
            shift = -shift;
            shifted.block(0, 0, rows, cols - shift) = input.block(0, shift, rows, cols - shift);
            shifted.block(0, cols - shift, rows, shift) = input.block(0, 0, rows, shift);
        }
    }
    return shifted;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值