3

Possible Duplicate:
How can I sort a 2-D array in MATLAB with respect to one column?
Sort a matrix with another matrix

I have a vector 'A' of 429 values and a matrix 'B' of 429x200 values. Rows in A and B are share the same indices. My vector 'A' contains values 1:1:429 but they are randomly ordered throughout the vector. I want to reorder A so that it indexes in order from 1 to 429 and I also want to sort the rows in matrix 'B' in the same order as the newly sorted 'A'.

Can this be done quick and easy without a for-loop?

Here's an example to illustrate my point:

A =
    5
    3
    1
    2
    4


 B =
    3   7   0   4   6
    1   2   5   0   8
    4   0   2   0   0
    3   0   1   0   5
    2   2   3   4   4


sortedA = 

1
2
3
4
5

sortedB =

4   0   2   0   0
3   0   1   0   5
1   2   5   0   8
2   2   3   4   4
3   7   0   4   6

Thank you everyone!

Community
  • 1
  • 1
thatWaterGuy
  • 315
  • 3
  • 12

1 Answers1

2

The example data:

A = [ 5, 3, 1, 2, 4 ]';

B = [ 3, 7, 0, 4, 6; 1, 2, 5, 0, 8; 4, 0, 2, 0, 0; 3, 0, 1, 0, 5; 2, 2, 3, 4, 4 ]

Sort the matrices:

[sortedA,IX] = sort(A);

sortedB = B(IX,:);

sortedA =
 1
 2
 3
 4
 5

sortedB =
 4     0     2     0     0
 3     0     1     0     5
 1     2     5     0     8
 2     2     3     4     4
 3     7     0     4     6
nrz
  • 10,435
  • 4
  • 39
  • 71