Sorting and indexing multidimensional arrays
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Shing Bo Peh
am 12 Nov. 2020
Bearbeitet: Shing Bo Peh
am 12 Nov. 2020
I would like to clarify if indexing is supported for multidimensional arrays.
For example, consider the code below.
According to the help page, the line B2 = A(I) a recover the sorted array.
However, from MATLAB Online R2020b the code snippet produces array full of ones as the result for B2.
A(:,:,1) = 1*ones(3);
A(:,:,2) = 2*ones(3);
A(:,:,3) = 3*ones(3);
A(:,:,4) = 4*ones(3);
[B,I] = sort(A,3,'descend');
B2 = A(I);
2 Kommentare
Stephen23
am 12 Nov. 2020
"According to the help page, the line B2 = A(I) a recover the sorted array."
Are your data in a vector? (hint: no).
Akzeptierte Antwort
Walter Roberson
am 12 Nov. 2020
See https://www.mathworks.com/matlabcentral/answers/645463-help-required-for-sorting#answer_542268 -- I just happened to write up an explanation for someone of the same basic problem.
You would need to expand what I wrote there into the third dimension. You would want to change the repmat() that I show there into something more like
[ROWIDX, COLIDX] = ndgrid(1:size(A,1), 1:size(A,2));
B2 = sub2ind(size(A), ROWIDX, COLIDX, sortidx);
This is untested; you might need to use meshgrid() instead of ndgrid()
3 Kommentare
Weitere Antworten (1)
Bruno Luong
am 12 Nov. 2020
Bearbeitet: Bruno Luong
am 12 Nov. 2020
[B,I] = sort(A,3,'descend');
I is ndarray same size as A and B, values is 1:size(A,3) such that for any i,j
A(i,j,I(i,j,:))
is equal to
B(i,j,:)
(Both are then sorted in descending order)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!