Sorting and indexing multidimensional arrays

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 件のコメント

Stephen23
Stephen23 2020 年 11 月 12 日
"According to the help page, the line B2 = A(I) a recover the sorted array."
What the sort documentation actually states is "if A is a vector, then B = A(I)" (emphasis added).
Are your data in a vector? (hint: no).
Shing Bo Peh
Shing Bo Peh 2020 年 11 月 12 日
Thanks for the explanation, indeed A is not a vector. Your comment and Walter's answer have been helpful in extending the example to 3D arrays.

サインインしてコメントする。

 採用された回答

Walter Roberson
Walter Roberson 2020 年 11 月 12 日

0 投票

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 件のコメント

Shing Bo Peh
Shing Bo Peh 2020 年 11 月 12 日
編集済み: Shing Bo Peh 2020 年 11 月 12 日
Thank you for the example.
The size of the inputs was slightly off in your comment but I found the below code to work after your explanation:
[ROWIDX,COLIDX,~]=ndgrid(1:size(A,1),1:size(A,2),1:size(A,3));
lix = sub2ind(size(A),ROWIDX,COLIDX,sortidx);
B2 = A(lix);
Many thanks for the help!
Edit: Change from meshgrid to ndgrid following Bruno's comment.
Walter Roberson
Walter Roberson 2020 年 11 月 12 日
Thanks for the test case, Bruno!
Shing Bo Peh
Shing Bo Peh 2020 年 11 月 12 日
Confirmed, thank you Bruno.

サインインしてコメントする。

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2020 年 11 月 12 日
編集済み: Bruno Luong 2020 年 11 月 12 日

1 投票

[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)

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

質問済み:

2020 年 11 月 12 日

編集済み:

2020 年 11 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by