How do I shift columns (left or right) in a matrix?

家住魔仙堡 提交于 2021-01-28 22:41:58

问题


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.

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

Thank you in advance


回答1:


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


来源:https://stackoverflow.com/questions/63320433/how-do-i-shift-columns-left-or-right-in-a-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!