# How to shift a matrix

100 views (last 30 days)
Aldo Hernandez on 11 Oct 2019
Answered: prasanth s on 11 Oct 2019
Say I have a matrix that is 3x3:
1 2 3
4 5 6
7 8 9
I want to shift the top and bottom rows:
1 2 3
4 5 6
7 8 9
This would expand it into a 3x4 matrix yes but i mostly want to know how specifically to do this shifting. I was told the imwarp function could help but im not sure. I'm thinking I would have to define a matrix for the first one to shift to? Or something like that?

Show 1 older comment
Aldo Hernandez on 11 Oct 2019
Cell array.
They way you have drawn your shifting suggests more than a 3x4 output as your shifted numbers fall in the gaps between the row below/above, which would require a larger matrix to include. Or are the 1, 5 and 7 supposed to all line up in the 2nd column?
Aldo Hernandez on 11 Oct 2019
Yes that is my bad. 1,5,7 are in same column as are 2,6,8. I'll edit that correction when I get the chancr.

prasanth s on 11 Oct 2019
loop version:
M=[ 1,2,3;
4,5,6;
7,8,9; ];
C=nan(3,4);
for i=1:size(M,1)
if mod(i,2)==1
C(i,2:end)=M(i,:);
else
C(i,1:end-1)=M(i,:);
end
end
vector slicing version:
M=[ 1,2,3;
4,5,6;
7,8,9; ];
L=mod([1:3]',2)>0;%logical 1 and 0 vector
A=M(L,:);
B=M(not(L),:);
C=nan(3,4);
C(L,2:4)=A;
C(not(L),1:3)=B;
M is input array
C is output array
empty elements is in 'NaN' type. you can get nan value index using 'isnan' function