Hi,
I have two 3d matrices (A and B) with the same size (m,n,o).
I want to sort matrix B along the third dimension based on the sort index of matrix A:
[~, idx] = sort(A,3,'descend')
If I use the following syntax it doesn't really work:
B = B(:,:,idx)
I get a (m,n,m*n*o) matrix instead of a sorted (m,n,o) matrix.
Any ideas?

 채택된 답변

Massimo Zanetti
Massimo Zanetti 2016년 10월 18일
편집: Massimo Zanetti 2016년 10월 18일

0 개 추천

According to Walter's comment, the previous solution was wrong. Here is a way to sort B given the sorted A along the 3-rd dimension:
m=3; n=4; o=2;
A=randi(9,m,n,o)
B(:,:,1)=[1,11,111,1111;2,22,222,2222;3,33,333,3333];
B(:,:,2)=[4,44,444,4444;5,55,555,5555;6,66,666,6666];
[~,ix] = sort(A,3,'descend');
[C,R,~]=meshgrid(1:n,1:m,1:o);
lix = sub2ind([m,n,o],R,C,ix);
B(lix)
Looking for a more general solution...

댓글 수: 6

No, the indices are relative to the layer, not absolute.
That's it! Thank you
Walter, you are right. Checking for solution.
A completely generic solution (ignoring potential edge cases such as A, B being vectors, etc):
function [sA, sB] = dualsort(A, B, dim, direction)
%dualsort, sort A according to dim and direction and sort B according to the order of A:
[sA, idx] = sort(A, dim, direction);
gridargs = arrayfun(@(s) 1:s, size(A), 'UniformOutput', false);
[gridargs{:}] = ndgrid(gridargs{:});
gridargs{dim} = idx;
sB = B(sub2ind(size(B), gridargs{:}));
end
Massimo Zanetti
Massimo Zanetti 2016년 10월 18일
편집: Massimo Zanetti 2016년 10월 18일
That is exactly the solution I have finally run into to generalize the one above. However, it seems quite surprising that apparently there is no something like "built-in" solution...
Andrei Bobrov
Andrei Bobrov 2016년 10월 18일
편집: Andrei Bobrov 2016년 10월 18일
[~, ii] = sort(A,3,'descend');
[m,n,o] = size(A);
B = B((ii-1)*m*n + reshape(1:m*n,m,[]));

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by