comparison scripts/general/sortrows.m @ 5178:6758c11b5b99

[project @ 2005-03-03 05:18:04 by jwe]
author jwe
date Thu, 03 Mar 2005 05:18:04 +0000
parents
children 41cd70503c72
comparison
equal deleted inserted replaced
5177:86fa011d6404 5178:6758c11b5b99
1 ## Copyright (C) 2000 Daniel Calvelo
2 ##
3 ## This program is free software; you can redistribute it and/or modify
4 ## it under the terms of the GNU General Public License as published by
5 ## the Free Software Foundation; either version 2 of the License, or
6 ## (at your option) any later version.
7 ##
8 ## This program is distributed in the hope that it will be useful,
9 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 ## GNU General Public License for more details.
12 ##
13 ## You should have received a copy of the GNU General Public License
14 ## along with this program; if not, write to the Free Software
15 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16
17 ## B = sortrows (A)
18 ## returns matrix with rows sorted "lexicographically"
19 ##
20 ## B = sortrows(A, c)
21 ## returns matrix with rows sorted according to the order of the
22 ## columns specified in c.
23 ##
24 ## Set implicit_str_to_num_ok and implicit_num_to_str_ok to 1 if you
25 ## use this for string sorting and octave 2.1.50 or earlier.
26
27 ## Author: Daniel Calvelo
28 ## 2001-02-24 Paul Kienzle
29 ## * cleanup according to Octave conventions
30 ## * return reverse index
31 ## * handle string arguments
32
33 function [s, i] = sortrows (m, c)
34
35 if nargin < 2
36 indices = [ 1 : size(m,2) ]';
37 else
38 indices = c (:);
39 endif
40
41 if (isstr (m))
42 s = toascii (m);
43 else
44 s = m;
45 endif
46
47 ## since sort is 'stable' the order of identical elements will be
48 ## preserved, so by traversing the sort indices in reverse order
49 ## we will make sure that identical elements in index i are subsorted
50 ## by index j.
51 indices = flipud (indices);
52 i = [1 : size(m,1)]';
53 for ii = 1 : length (indices);
54 [ trash, idx ] = sort ( s ( : , indices (ii) ) );
55 s = s ( idx, : );
56 i = i (idx );
57 endfor
58 if (isstr (m))
59 s = setstr(s);
60 endif
61 endfunction