how to reorder the elements of a matrix

A=[1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16]
i want to reorder the elements of A into
A=[16 15 12 8
11 14 13 10
7 4 3 6
9 5 2 1 ]

6 Comments

zigzag pattern starting from 16th element
I do not see the pattern once you get beyond 5 going upwards, or below 12 going downwards ?
Is this intended to be the zig-zag pattern used in JPEG ?
the pattern is like, reverse zigzag pattern, the first row 16 15 12 8, second row 11 14 13 10, third row 7 4 3 6 and last row 9 5 2 1
What would your pattern be if A were 5x5, 6x6, or nxn? Are you interested in generalizing in that manner?
only for 4 x 4 matrix

Sign in to comment.

Answers (2)

Star Strider
Star Strider on 29 Mar 2014
Edited: Star Strider on 29 Mar 2014
Here’s one solution. I have no idea if it can be generalised to other matrices.
B = flipud(A)
dl = size(A,1);
C = [];
for k1 = sum(size(A))-1 : -1 : 1
dg = diag(B,k1-dl)
if mod(k1,2) == 1
dg = flipud(dg)
end
C = [C; dg]
end
D = reshape(C,size(A))'
Here's a one-liner, though it doesn't exhibit the ingenuity that Star's does.
A = A([16,12,15,14;11,8,4,7;10,13,9,6;3,2,5,1]);
Like Star, I have no idea how this is supposed to generalize. I think you will have to give many more examples or else a more thorough explanation than "zig-zag" if the logic behind this request is to be understood, Alina.

2 Comments

Nice and simple. She did not ask for it to be generalized. Hence, this is what she gets as the most direct answer. If she comes back and says "how can I generalize?" then you can say "Well, why didn't you say so in the beginning!?!?"
Sagar Damle
Sagar Damle on 30 Mar 2014
Edited: Sagar Damle on 31 Mar 2014
I think to generalize the answer for this question,one can work on code for function 'pascal()' available in MATLAB.I have not got the logic in that code uptil now,but though I think that the code will help in zig-zag coding.

Sign in to comment.

Categories

Products

Asked:

on 29 Mar 2014

Edited:

on 31 Mar 2014

Community Treasure Hunt

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

Start Hunting!