sort(X,dim)
sorts along dimension dim
, i.e. sort(X,1)
sorts the rows within each column, and sort(X,2)
sorts the columns within each row. sortrows(X,4)
sorts the rows according to the fourth row, and if you want to sort the columns, you have to transpose X
first.
sort(X(:)
sorts all the elements of the array X
.
- In this code, all the elements of
img2
are shuffled.
Instead of using autumn.tif
, you may want to try shuffling on e.g. magic(5)
, a 5x5 magic square, so that you can better see what is going on.
EDIT
Here are the examples with magic(5)
>> m = magic(5)
m =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> sort(m,1) %# sort rows in each column of m
ans =
4 5 1 2 3
10 6 7 8 9
11 12 13 14 15
17 18 19 20 16
23 24 25 21 22
>> sort(m,2) %# sort columns in each row of m
ans =
1 8 15 17 24
5 7 14 16 23
4 6 13 20 22
3 10 12 19 21
2 9 11 18 25
>> sortrows(m,3) %# sort the rows of m according to column 3
ans =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> mt = m' %'# transpose m
mt =
17 23 4 10 11
24 5 6 12 18
1 7 13 19 25
8 14 20 21 2
15 16 22 3 9
>> sortrows(mt,2) %# sort the rows of the transpose of m according to col 2
ans =
24 5 6 12 18
1 7 13 19 25
8 14 20 21 2
15 16 22 3 9
17 23 4 10 11
>> mm = m; %# assign an output array for the next operation
>> mm(:) = sort(m(:)) %# sort all elements of m
mm =
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25