how to reorder the elements of a matrix
1 view (last 30 days)
Show older comments
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
Roger Stafford
on 30 Mar 2014
What would your pattern be if A were 5x5, 6x6, or nxn? Are you interested in generalizing in that manner?
Answers (2)
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))'
0 Comments
Roger Stafford
on 29 Mar 2014
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
Image Analyst
on 30 Mar 2014
Edited: Image Analyst
on 30 Mar 2014
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
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.
See Also
Categories
Find more on Sparse Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!