Sorting matrices in matlab

Hello,
I have a NxM matrix:
Random A for example 10x5
A =
2 8 7 1 4
9 8 8 1 7
4 8 2 8 8
3 3 2 10 6
8 7 6 7 8
1 6 5 2 3
1 4 9 8 8
7 1 8 2 10
7 8 8 2 9
6 4 1 7 1
I would like to make another matrix (B) that contains first every N, N+2, N+4...and after them N+1,N+3.. ect
B =
2 8 7 1 4
4 8 2 8 8
8 7 6 7 8
1 4 9 8 8
7 8 8 2 9
9 8 8 1 7
3 3 2 10 6
1 6 5 2 3
7 1 8 2 10
6 4 1 7 1
Thank you.

1 Comment

Note that this is a topic of indexing/rearranging the elements, where the element values are not relevant to the new order (only their indices are). Sorting depends only on the element values (not their indices).

Sign in to comment.

 Accepted Answer

>> B = A([1:2:end,2:2:end],:)
B =
2 8 7 1 4
4 8 2 8 8
8 7 6 7 8
1 4 9 8 8
7 8 8 2 9
9 8 8 1 7
3 3 2 10 6
1 6 5 2 3
7 1 8 2 10
6 4 1 7 1

4 Comments

What if I have for example 14 rows between each other? Is there some loop or I have to write
B = A([1:14:end,2:14:end,3:14:end,4:14:end....14:14:end],:)
@Matija Kosak: I would use reshape and permute to generalize this (note that the number of rows N has to be exactly divisible by R):
>> A = randi(99,12,5) % size NxM
A =
35 89 14 49 65
76 33 18 98 14
29 59 53 29 54
63 69 51 27 50
21 96 86 17 55
60 14 56 30 54
40 16 17 43 60
62 73 78 80 3
37 31 23 84 54
8 17 26 72 29
62 54 55 46 2
31 67 1 99 29
>> R = 4; % N must be divisible by R.
>> S = size(A);
>> B = reshape(permute(reshape(A,R,[],S(2)),[2,1,3]),S)
B =
35 89 14 49 65
21 96 86 17 55
37 31 23 84 54
76 33 18 98 14
60 14 56 30 54
8 17 26 72 29
29 59 53 29 54
40 16 17 43 60
62 54 55 46 2
63 69 51 27 50
62 73 78 80 3
31 67 1 99 29
>> C = A([1:4:end,2:4:end,3:4:end,4:4:end],:) % needs to match this!
C =
35 89 14 49 65
21 96 86 17 55
37 31 23 84 54
76 33 18 98 14
60 14 56 30 54
8 17 26 72 29
29 59 53 29 54
40 16 17 43 60
62 54 55 46 2
63 69 51 27 50
62 73 78 80 3
31 67 1 99 29
>> isequal(B,C)
ans = 1
That's not good for what I need because it mix numbers. I would need for numbers in rows to be same.
It works now, thank you a lot :)

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!