MATLAB: Help with matrix indexing and tricking

matrix indexingsorttrick

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

Best Answer

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