Say you have a 1D matrix
a = rand(1,5); [sa i] = sort(a);
then sa and a(i) coincide. However, if the size of the matrix increases
a = rand(3,4); [sa i] = sort(a);
then sa and a(i) do not coincide. And the same thing happens when I try to sort a 3D matrix by its third dimension.
How to access values โโof a through index i ? Or, in other words, how can I calculate sa=a(X) what X should be?
Edit:
Thanks for the solution. However, they do not work when you change the dimension to sort. However, I take this idea and use it to create a common form.
What the algorithm does is build matrix indices. MATLAB indexes cell columns. Therefore, the index is specified
idx = r + (c-1)*ROWS + (p-1)*ROWS*COLS
where, idx is the index, r is the position of the row, c is the position of the column, and p is the position of the page.
Therefore, if we sort in the first dimension (normal sort(a) ), then the result is the position in the columns; if we sort in the second dimension, the index of the result is the position in the rows; and if we sort in the third dimension, then the result is the position of the page. Saying this, he only last time creates rows and columns for this 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 let's 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 to sort in the third dimension (per page), 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 expand it to N dimensions. Thanks for your help, you burn the way. :)