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

조회 수: 69 (최근 30일)
NA
NA 2020년 8월 8일
댓글: NA 2020년 8월 8일
Hi All,
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.
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;
chDiff = layerIV - channelSink;
for channel = 1:16
if channelSink > layerIV
%shift columns to the left by ab(chDiff)
%and
%set columns shifted by ab(chDiff) to zero
elseif channelSink < layerIV
%shift columns to the right by chDiff
%and
%set columns shifted by chDiff to zero
else %if chDiff = 0, don't shift
chDiff = 0;
disp('Sink at channel 7; not necessary to re-align');
end
end
Thank you in advance.

채택된 답변

Walter Roberson
Walter Roberson 2020년 8월 8일
shift = abs(diff)
%left
data = [data(:, shift+1:end), zeros(size(data,1),shift)]
%right
data = [zeros(size(data,1),shift), data(:, end-shift:shift)];
Note: we recommend against using diff() as a variable name, as it conflicts with the common function diff() . If nothing else, it will tend to confuse other people who read your code.
  댓글 수: 3
Walter Roberson
Walter Roberson 2020년 8월 8일
%right
data = [zeros(size(data,1),shift), data(:, shift:end-shift)];
NA
NA 2020년 8월 8일
Thank you, Walter. I just made a tiny adjustment as the shifted columns were off by 1.
data = [zeros(size(data,1),shift), data(:, shift-1:end-shift)];
But, it works perfectly now. Thanks again!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Abdolkarim Mohammadi
Abdolkarim Mohammadi 2020년 8월 8일
편집: Abdolkarim Mohammadi 2020년 8월 8일
I used the vectorization capability of MATLAB, so it is faster and there is no need for a for loop.
data = rand (5,16);
channelSink = 9; % this variable will either be >layerIV, <layerIV or =layerIV
layerIV = 7;
diff = layerIV - channelSink;
dataFirstCol = 1;
dataLastCol = size (data,2);
dataShiftedFirstCol = 1;
dataShiftedLastCol = size (data,2);
if diff < 0
dataFirstCol = dataFirstCol + abs(diff);
dataShiftedLastCol = dataShiftedLastCol - abs(diff);
elseif diff > 0
dataLastCol = dataLastCol - abs(diff);
dataShiftedFirstCol = dataShiftedFirstCol + abs(diff);
end
dataShifted = zeros (size(data));
dataShifted (:,dataShiftedFirstCol:dataShiftedLastCol) = data (:,dataFirstCol:dataLastCol);
  댓글 수: 1
NA
NA 2020년 8월 8일
Thanks for this. The reason I wrote my code in a for loop was because I need to run it on multiple datasets (n x 16 matrix). But I will try and adapt what you have done to suit what I want. I do apprecaite your help.

댓글을 달려면 로그인하십시오.


Bruno Luong
Bruno Luong 2020년 8월 8일
k > 0 shift right
k < 0 shift left
A*diag(ones(1,size(A,2)-abs(k)),k)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by