필터 지우기
필터 지우기

Sorting a Matrix using Indices from another matrix !

조회 수: 21 (최근 30일)
Dimitris M
Dimitris M 2013년 9월 13일
댓글: Aaron Thode 2018년 7월 31일
Hello
I have a pretty simple question !
I have a matrix A (lets assume has a size 5 x 5) and I have another matrix of same size (5 x 5) called IDX that contains the values for sorting A in a colum-wise manner.
So how can I easily sort each column of A using matrix IDX without using a for loop or extracting each column of IDX as an individual vector ?
Thank you in advance !
  댓글 수: 2
the cyclist
the cyclist 2013년 9월 13일
This would be much easier to answer if you gave examples of the two matrices, and the expected result.
Dimitris M
Dimitris M 2013년 9월 13일
편집: Image Analyst 2013년 9월 13일
Ok sure
A = [1 1 1 0 0 0;
0 0 0 1 1 1;
0 1 0 1 0 1]'
IDX = [4 5 6 3 2 1;
1 2 3 6 5 4;
6 5 4 3 2 1]'
And I want to sort A using the indices of IDX in a columnwise manner!
Is it clear enough now?

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

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 9월 13일
[m,n]=size(A);
A=A(sub2ind([m n],idx,repmat(1:n,m,1)))
  댓글 수: 5
Azzi Abdelmalek
Azzi Abdelmalek 2013년 9월 13일
idx =[4 1 6;5 2 5;6 3 4;3 6 3;2 5 2;1 4 1];
A = [1:6;7:12;13:18]';
idx1=idx % indicate line index
4 1 6
5 2 5
6 3 4
3 6 3
2 5 2
1 4 1
[m,n]=size(A);
idx2=repmat(1:n,m,1) %indicate column index
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
idx=sub2ind([m n],idx1,idx2) % to get linear index
4 7 18
5 8 17
6 9 16
3 12 15
2 11 14
1 10 13
A=A(idx)
Aaron Thode
Aaron Thode 2018년 7월 31일
Very impressive; I've wondered about this for a long time. Thank you!

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

추가 답변 (2개)

Image Analyst
Image Analyst 2013년 9월 13일
Try this:
% Create random sample data so it will be easy
% for us to see if the sorting worked.
A = randi(9, [6,3])
IDX = [4 5 6 3 2 1;
1 2 3 6 5 4;
6 5 4 3 2 1]'
[rows, columns] = size(A)
% Sort columns of A according to the same column of IDX
for col = 1 : columns
A(:,col) = A(IDX(:,col), col);
end
% Print out to command window.
A
In the command window:
A =
7 7 7
3 8 7
9 2 3
1 5 7
4 5 6
4 6 2
IDX =
4 1 6
5 2 5
6 3 4
3 6 3
2 5 2
1 4 1
rows =
6
columns =
3
A =
1 7 2
4 8 6
4 2 7
9 6 3
3 5 7
7 5 7

Azzi Abdelmalek
Azzi Abdelmalek 2013년 9월 13일
편집: Azzi Abdelmalek 2013년 9월 13일
Edit2
A = [1 1 1 0 0 0; 0 0 0 1 1 1; 0 1 0 1 0 1]'
idx= [4 5 6 3 2 1; 1 2 3 6 5 4; 6 5 4 3 2 1]'
[m,n]=size(A);
idx=bsxfun(@plus,idx,(0:m:(n-1)*m))
A=A(idx)

카테고리

Help CenterFile 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