MATLAB: Trying to make a “snake” matrix

loopsmatrix arraymatrix manipulation

N=5;
M=9;
T=zeros(N,M);
count=0;
for i=1:N
for j=1:M
count=count+1;
T(i,j)=count;
if mod(i,2)==0
T(i,j)=fliplr(T(i,j));
end
end
end
T
I'm trying to get the even rows to go 1,2,3,4 and so on to the last column, and then on the even rows I want the elements to flip from left to right. SO far I've got a matrix that goes from 1 to the last element, and I can't seem to get the even rows to flip. Thanks!

Best Answer

N = 5; M = 9;
T = reshape(1:M*N, [M, N])';
T(2:2:end,:) = fliplr(T(2:2:end,:));