Let's said you have a 1D matrix
a = rand(1,5);
[sa i] = sort(a);
then sa
and a(i)
are the same. However, if the size of the matrix increases
a = rand(3,4);
[sa i] = sort(a);
then sa
and a(i)
are not the same. And the same happens when I'm trying to sort a 3D matrix by its third dimension.
How can I access the values of a
through the index i
? Or in other words how can I compute the sa=a(X)
, what X
should be?
Edit:
Thanks for the solutions. However, they don't work when you change the dimension to sort by. Nevertheless, I pick up the idea and use it to build a general form.
What the algorithm is doing is to build the indexes of the matrix. MATLAB index the cells column wise. Therefore, the index is given by
idx = r + (c-1)*ROWS + (p-1)*ROWS*COLS
where, idx
is the index, r
is the row position, c
is the column position, and p
is the page position.
Therefore, if we sort in the first dimension (normal sort(a)
) the result index is the position in the columns; if we sort in the second dimension, the result index is the position in the rows; and if we sort in the third dimension, the result index is the page position. This being said, it only last to produce the rows and cols for the given case:
r = repmat((1:rows)',[1 cols pages]);
c = repmat(1:cols,[rows 1 pages]);
Sorting in the first dimension is explained in the solutions given. Then, lets sort in the second dimension (row wise) of a two dimensional array
a = rand(4,5);
[rows cols pages] = size(a);
R = repmat((1:rows)',[1 cols pages]);
[sa idx] = sort(a,2);
nIdx = R + (idx-1)*rows;
isequal(sa,a(nIdx))
Now, if we use the same idea for sorting in the third dimension (page wise), we need to do
a = rand(4,5,3);
[rows cols pages] = size(a);
R = repmat((1:rows)',[1 cols pages]);
C = repmat(1:cols,[rows 1 pages]);
[sa idx] = sort(a,3);
nIdx = R + (C-1)*rows + (idx-1)*rows*cols;
isequal(sa,a(nIdx))
And the same logic can be used to extend it to N dimensions. Thanks for your help, you en light the way. :)