CinelliT
CinelliT

Reputation: 27

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

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

Upvotes: 1

Views: 266

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112689

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

Upvotes: 3

Related Questions