[Scilab-users] sort a table/matrix

Stefan Du Rietz sdr at durietz.se
Sat Nov 10 17:32:53 CET 2012


On 2012-11-10 16:39, Samuel Gougeon wrote:
--------------------
> Le 10/11/2012 15:06, Paul Carrico a écrit :
>>
>> D= [
>>
>> 10 3 11 10 13;
>>
>> 49 6 -1 -1 0;
>>
>> 178 39 9 -451 3;
>>
>> 10110 -12 1 -9 45 ;
>>
>> -13514 15 78 -99 3]
>>
>> /// each line is sorted from the 1rst column (in increasing order)/
>>
>> D_expeted= [
>>
>> -13514 15 78 -99 3;
>>
>> 10 3 11 10 13;
>>
>> 49 6 -1 -1 0;
>>
>> 10110 -12 1 -9 45;
>>
>> 178 39 9 -451 3;
>>
>> ]
>>
> gsort(D,"lr","i")
>
> will do it.
>
But if you want to sort only according to the first column (or certain 
columns) and keep the original order independently of the other 
columns (which I often need), you have to do it in two steps:

-->A=[3 4 1; 3 3 2; 2 2 3; 1 1 4]
  A  =
     3.    4.    1.
     3.    3.    2.
     2.    2.    3.
     1.    1.    4.
1. Sort only the first column and get the sort order (with "lr" as the 
second argument, you can use a vector of several columns for the 
second index of A):
-->[B,k]=gsort(A(:,1),"lr","i")
  k  =
     4.
     3.
     1.
     2.
2. Rearrange the rows with k:
-->A=A(k,:)
  ans  =
     1.    1.    4.
     2.    2.    3.
     3.    4.    1.
     3.    3.    2.
Note the original order of the last two rows, contrary to
-->gsort(A,"lr","i")
  ans  =
     1.    1.    4.
     2.    2.    3.
     3.    3.    2.
     3.    4.    1.

Stefan





More information about the users mailing list