Search code examples
matlaboctave

Sorting two columns of a matrix while keeping one intact in OCTAVE/MATLAB


I have this matrix:

data=[1 5402783   1   
      2 43359352  2   
      3 26118700  3   
      4 33091887  4   
      5 890931    5   
      6 826897    6   
      7 1188749   7   
      8 1239861   8];

I need the first column to stay as it is, sort the 2nd column (in descending order) and 'keep along' the values of the third column. If I use sort(data) it sorts all 3 columns.

I tried:

[~,idx]=sort(data(:,2),'descend');  
data=data(idx,:) 

but it is obviously wrong.

The output should be:

[1   43359352          2  
 2   33091887          4  
 3   26118700          3  
 4    5402783          1  
 5    1239861          8  
 6    1188749          7  
 7     890931          5  
 8     826897          6]  

Solution

  • All you need to do is reassemble the data matrix in the end taking the unsorted and sorted parts:

    data = [1 5402783  1
            2 43359352 2
            3 26118700 3
            4 33091887 4
            5 890931   5
            6 826897   6
            7 1188749  7
            8 1239861  8];
    
    [~,idx] = sort(data(:,2),'descend');
    data = [data(:,1),data(idx,2:3)];