Wednesday, January 16, 2013

rearrange a matrix according to sorting of a vector

Imagine I have the following matrix-vector correspondence where I want to sort the vector and then rearrange the matrix according to the sorted order of vector maintaining the correspondences.


Initial matrix vector correspondences are
MatrixA vector 
1 2 4
3 4 1
5 6 3
7 8 2


Step1: Lets sort B first keeping the indexes


[sortedB,indexB]=sort(B)

sortedB =

     1
     2
     3
     4


indexB =

     2
     4
     3
     1
Step2: rearrange matrixA according to indexB

>> A(indexB,:)

ans =

     3     4
     7     8
     5     6
     1     2

Correspondence are maintained as the initial state


rearrangeA sorted vector
3 4     1
7 8      2
5 6      3
1 2      4

No comments:

Post a Comment

Please ask if anything is not clear enough..........