2

Suppose I have two matrices p

p =
 1     3     6     7     3     6
 8     5    10    10    10     4
 5     4     8     9     1     7
 5     5     5     3     8     9
 9     3     5     4     3     1
 3     3     9    10     4     1

then after sorting the columns of matrix p into ascending order

y =  
 1     3     5     3     1     1
 3     3     5     4     3     1
 5     3     6     7     3     4
 5     4     8     9     4     6
 8     5     9    10     8     7
 9     5    10    10    10     9

I want to know, given a value from y, what its row was in p

ex: the value 3 which is in matrix p located in row 6 column 1

then after sorting it located in matrix y in row 2 column 1

So I want at the end the values after sorting in matrix y, where it was originally in matrix p

Joe
  • 457
  • 5
  • 18

3 Answers3

1

The Matlab sort command returns a second value which can be used to index into the original array or matrix. From the sort documentation:

[Y,I] = sort(X,DIM,MODE) also returns an index matrix I.
If X is a vector, then Y = X(I).  
If X is an m-by-n matrix and DIM=1, then
    for j = 1:n, Y(:,j) = X(I(:,j),j); end
Daniel Golden
  • 3,752
  • 2
  • 27
  • 32
1

Just use second output of sort:

[y ind] = sort(p);

Your desired result (original row of each value) is in matrix ind.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

Ok i understand exactly what you want.

I will give you my code that i write now, it is not optimal but you can optimize it or i can work with you in order to get the better code..

P and y have the same size.

    [n,m]=size(p);

    for L=1:m
    i=1;
    temp=y(i,L);
    while(i<=n)
    if(temp==y(i,L))
    % So it is present in case i of p
    disp(['It is present in line' num2str(i) ' of p']);

    end
    i=i+1;
    end
    end

Voilà!!

Christina
  • 903
  • 16
  • 39