0

Possible Duplicate:
Sort a matrix with another matrix

The Matrix A ('10 x 1000' all numbers) look like this:

score(1.1) score(1.2) score(1.3)....score(1.1000)

score(2.1) score(2.2) score(2.3)....score(1.1000)

...

The Matrix B ('1 x 1000' all numbers):

Return(1) Return(2) Return(3) .....Return(1.1000)

Every time I sort a row of Matrix A, I want to sort Matrix B based on the order of the sorted row in Matrix A. Because there are 10 rows in Matrix A, Matrix B will be sorted 10 times and generate a new Matrix C ('10 x 1000') like this: (I am looking for a script to generate this Matrix C)

Return(3) Return(25) Return(600) .......Return(1000)

Return(36)Return(123) Return(2)........Return(212)

.... ....

Community
  • 1
  • 1
user1205030
  • 215
  • 1
  • 7
  • 14

3 Answers3

1

This should do what you want:

A = randn(10,1000);
B = randn(1,1000);
C = zeros(size(A));

for i = 1:10
    [a idx] = sort(A(1,:));
    A(i,:) = a;
    C(i,:) = B(idx);
end

Now the rows of A are sorted, and the rows of C contain the corresponding sorted B.

Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
1

This solution is a bit more compact, and it's also good to get used to doing this kind of solution for efficiency when your matrices get big. You can solve your problem with two ideas:

  1. In [a, ix] = sort(X), a is a column-sorted version of X, and ix stores which rows moved where in each column. Thus if we do [a, ix] = sort(X.').'; (where the dot-apostrophe is the transpose) we can sort the rows.
  2. B(ix) where ix is a bunch of indeces will make a matrix the same size as ix with the i-jth element being B at ix(i,j)

Then you just need to reshape it. So you can do:

A = rand(4,8);
B = rand(1,8);
n = size(A,1);
m = size(A,2);

[~,ix] = sort(A.');
C = reshape(B(ix'),n,m);
Ian Hincks
  • 3,608
  • 3
  • 23
  • 20
0

If I understand your question correctly the following should work. Using some sample scores:

>> score = [1 4 7 9; 3 5 1 7; 9 3 1 6]

score =

     1     4     7     9
     3     5     1     7
     9     3     1     6

and sample return vector:

>> r = [10 20 30 40]

r =

    10    20    30    40

Transpose the scores and sort since the SORT command works on columns of a matrix. We're only interested in the indices of the sorted values:

>> [~, ix] = sort(score')

ix =

     1     3     3
     2     1     2
     3     2     4
     4     4     1

Now transpose these indices and use them to reference the return values:

>> answer = r(ix)'

answer =

    10    20    30    40
    30    10    20    40
    30    20    40    10
b3.
  • 7,094
  • 2
  • 33
  • 48