help with matrix indexing and tricking

1 view (last 30 days)
Say I have a random matrix (A) [8 6 2 5; 9 6 7 1; 3 9 5 7]
Then I sort them and with index vector output
[B,Rid] = sort(A,2)
Then I should have the output
B = [2 5 6 8 ; 1 6 7 9 ; 3 5 7 9]
Rid = [3 4 2 1 ; 4 2 3 1 ; 1 3 4 2]
If I have another matrix C = [ 5 6 2 1 ; 5 6 7 8 ; 1 2 3 4 ]
I'd like to create a new matrix D by arranging the value in C base on the the index vector RID
for example
D = [ 2 1 6 5 ; 8 6 7 5 ; 1 3 4 2 ]
I can't figure the code

Accepted Answer

Star Strider
Star Strider on 27 Jan 2015
I couldn’t avoid a loop, but this works:
A = [8 6 2 5; 9 6 7 1; 3 9 5 7];
[B,Rid] = sort(A,2);
C = [ 5 6 2 1 ; 5 6 7 8 ; 1 2 3 4 ];
for k1 = 1:size(C,1)
D(k1,:) = C(k1,Rid(k1,:));
end

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!