2

I am trying to sort an array based on another array. I tried the sort method with index return, but it is somehow behaving strangely.

y = [1 2 3; 2 3 4] 
x = [1 3 4; 2 2 3] 
[yy, ii] = sort(y,'descend');

yy =
   2     3     4   
   1     2     3

ii =
   2     2     2
   1     1     1

But my x(ii) is not the matrix sorted based on y.

x(ii) =  
      2     2     2
      1     1     1

I am expecting the matrix to be:

x(ii) =

    2     2     3 
    1     3     4

How can I sort the matrix x according to another matrix y?

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
Shew
  • 1,557
  • 1
  • 21
  • 36
  • 1
    Possible duplicate of [Sort a matrix with another matrix](https://stackoverflow.com/questions/2679022/sort-a-matrix-with-another-matrix) – Wolfie Sep 17 '18 at 08:03

1 Answers1

8

ii are row subscripts but are being inputted by you as linear indices. You need to convert them to relevant linear indices before proceeding i.e.

>> szx =  size(x);
>> x(sub2ind(szx, ii, repmat(1:szx(2),szx(1),1)))

ans =

     2     2     3
     1     3     4
Sardar Usama
  • 19,536
  • 9
  • 36
  • 58