This is in continuation to a question Image Shuffling in one of my threads.
%# scramble autumn.tif with itself
img1 = imread('autumn.tif');
%# scramble
[dummy,scrambleIdx] = sort(img1(:));
img2 = img1;
img2(:) = img1(scrambleIdx); %# note the (:). If you don't use it, img2 becomes a vector
%# unscramble
[dummy2,unscrambleIdx] = sort(scrambleIdx);
img3 = img2;
img3(:) = i开发者_Python百科mg2(unscrambleIdx);
Question 1: The sort(X,dim)
function arranges the columns of X in ascending order. Does this imply all dimensions of X?
Question 2: Are both columns and rows of img2 shuffled in this code, or only the columns?
sort(X,dim)
sorts along dimensiondim
, i.e.sort(X,1)
sorts the rows within each column, andsort(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 transposeX
first.sort(X(:)
sorts all the elements of the arrayX
.- 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
精彩评论