# "Sort 3_D array along the third dimension"

2 views (last 30 days)
alpedhuez on 15 Jul 2022
Answered: Steven Lord on 15 Jul 2022
https://www.mathworks.com/help/matlab/ref/sort.html has an example of "Create a 2-by-2-by-2 array and sort its elements in ascending order along the third dimension." What does "along the third dimension" mean?
Bruno Luong on 15 Jul 2022
it means for any valid (i, j)
v = squeeze(A(i,j,:))
is sorted.

Steven Lord on 15 Jul 2022
If you look at the pictures in the description of the dim input argument on that page, note that the arrows go down along the columns (for dimension 1) and across the rows (for dimension 2.) If we had a similar picture for dimension 3, the arrows would be poking out of the screen.
Another analogy: take a deck of playing cards and deal out 24 cards in 6 stacks (two rows and three columns) with 4 cards in each stack. Sorting that 2-by-3-by-4 array along the third dimension would require sorting each stack of 4 cards independently, without moving any cards to a different stack.
rng default % for reproducibility
x = reshape(randperm(24), [2 3 4])
x =
x(:,:,1) = 22 3 11 6 16 7 x(:,:,2) = 17 8 21 14 5 19 x(:,:,3) = 15 23 4 1 2 18 x(:,:,4) = 24 9 10 13 20 12
s = sort(x, 3)
s =
s(:,:,1) = 15 3 4 1 2 7 s(:,:,2) = 17 8 10 6 5 12 s(:,:,3) = 22 9 11 13 16 18 s(:,:,4) = 24 23 21 14 20 19
The stack s(2, 1, :) has 2 in the first page, 5 in the second, 16 in the third, and 20 in the fourth. In x, those elements were arranged as {16, 5, 2, 20} instead.
Based on something you asked in a different question, I think you expected this to sort a matrix by its third column. If so, that's the type of problem you'd use sortrows for.
B = reshape(randperm(12), [3 4])
B = 3×4
8 6 5 3 10 9 1 2 11 4 7 12
Bsorted = sortrows(B, 2)
Bsorted = 3×4
11 4 7 12 8 6 5 3 10 9 1 2
The second column of B is [6; 9; 4]. When you sort B by that column the third row of B becomes the first row of Bsorted, the first row of B becomes the second row of Bsorted, and the second row of B becomes the third row of Bsorted.

Torsten on 15 Jul 2022
It means that B(:,:,1) <= B(:,:,2) is arranged by ordering the vectors [2,-1], [3,9],[1,0] and [6,12].
alpedhuez on 15 Jul 2022
I thought it is like "fix the third dimension." But it is not. What is fixed here?

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!

Translated by