如何在矩阵中移动列(左或右)? [英] How do I shift columns (left or right) in a matrix?

查看:129
本文介绍了如何在矩阵中移动列(左或右)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想非循环地移动矩阵,然后向左或向右填充零(取决于移动),即,如果矩阵向右移动,则将零向左填充.

I would like to non-circularly shift my matrix and then have zeros padded to either the left or right (depending on the shift) i.e. if the matrix shifts to the right, zeros would be padded to the left.

我正在使用MATLAB 2019b,到目前为止我的代码看起来像这样:

I am using MATLAB 2019b and my code so far looks like this:

%dummy data
data = rand(5, 16);

channelSink = 9; %this variable will either be >layerIV, <layerIV or =layerIV
layerIV = 7;
diff = layerIV - channelSink;

for channel = 1:16
    
        if channelSink > layerIV 
            
            %shift columns to the left by ab(diff)
            %and
            %set columns shifted by ab(diff) to zero
            
        elseif channelSink < layerIV
            
            %shift columns to the right by diff
            %and
            %set columns shifted by diff to zero
            
        else %idiff = 0, don't shift
              
              diff = 0; 
              disp('Sink at channel 7; not necessary to re-align');
             
        end
        
    end

提前谢谢

推荐答案

这将矩阵 data 水平移动 d 个位置,如果 d 为正,如果为负则向左,在另一侧填充零:

This horizontally shifts a matrix data by d positions, to the right if d is positive or to the left if negative, padding the other side with zeros:

data = rand(5, 16); % example matrix
d = 3; % shift; positive/negative for right/left
result = zeros(size(data), 'like', data); % preallocate with zeros
result(:,max(1,1+d):min(end,end+d)) = data(:,max(1,1-d):min(end,end-d)); % write values

这篇关于如何在矩阵中移动列(左或右)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆