2014-11-23 59 views
1

我有set4變量(4 x 2雙)。當我對它進行排序時,每個元素的第二個屬性也被排序。我只需要排序第一個屬性。 例如,排序後無法保留第二個屬性

set4=[ 10 1; 20 1; 5 2; 15 2]; 
sort(set4) 

輸出:

ans = 

    5  1 
    10  1 
    15  2 
    20  2 

但是我預期的輸出, ANS =

5  2 
10  1 
15  2 
20  1 

我該怎麼辦呢?

回答

1
set4=[ 10 1; 20 1; 5 2; 15 2]; %example data 
[set,in] = sort(set4(:,1)); %sort just the first column and get the indices 
set(:,2)= set4(in,2)   %use the indices to re-order the second column 
set = 

5  2 
10  1 
15  2 
20  1 
0
set4=[ 10 1; 20 1; 5 2; 15 2]; 
sortrows(set4) 

ans= 

5  2 
10  1 
15  2 
20  1