7017
|
1 ## Copyright (C) 2000, 2005, 2007 Daniel Calvelo |
5178
|
2 ## |
5181
|
3 ## This file is part of Octave. |
5178
|
4 ## |
5181
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
5181
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
5178
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
5178
|
18 |
5182
|
19 ## -*- texinfo -*- |
|
20 ## @deftypefn {Function File} {} sortrows (@var{a}, @var{c}) |
|
21 ## Sort the rows of the matrix @var{a} according to the order of the |
|
22 ## columns specified in @var{c}. If @var{c} is omitted, a |
7678
|
23 ## lexicographical sort is used. By default ascending order is used |
|
24 ## however if elements of @var{c} are negative then the corrosponding |
|
25 ## column is sorted in descending order. |
5182
|
26 ## @end deftypefn |
5178
|
27 |
5181
|
28 ## Author: Daniel Calvelo, Paul Kienzle |
|
29 ## Adapted-by: jwe |
5178
|
30 |
|
31 function [s, i] = sortrows (m, c) |
7678
|
32 |
|
33 default_mode = "ascend"; |
|
34 other_mode = "descend"; |
5181
|
35 if (nargin < 2) |
|
36 indices = [1:size(m,2)]'; |
7678
|
37 mode{1:size(m,2)} = default_mode; |
5178
|
38 else |
7678
|
39 for ii = 1:length (c); |
|
40 if (c(ii) < 0) |
|
41 mode{ii} = other_mode; |
|
42 else |
|
43 mode{ii} = default_mode; |
|
44 endif |
|
45 endfor |
|
46 indices = abs(c(:)); |
5178
|
47 endif |
|
48 |
5443
|
49 if (ischar (m)) |
5178
|
50 s = toascii (m); |
|
51 else |
|
52 s = m; |
|
53 endif |
|
54 |
5181
|
55 ## Since sort is 'stable' the order of identical elements will be |
|
56 ## preserved, so by traversing the sort indices in reverse order we |
|
57 ## will make sure that identical elements in index i are subsorted by |
|
58 ## index j. |
5178
|
59 indices = flipud (indices); |
7678
|
60 mode = flipud (mode'); |
5181
|
61 i = [1:size(m,1)]'; |
|
62 for ii = 1:length (indices); |
7678
|
63 [trash, idx] = sort (s(:,indices(ii)), mode{ii}); |
5181
|
64 s = s(idx,:); |
|
65 i = i(idx); |
5178
|
66 endfor |
5181
|
67 |
5443
|
68 if (ischar (m)) |
|
69 s = char (s); |
5178
|
70 endif |
5181
|
71 |
5178
|
72 endfunction |
7678
|
73 |
|
74 %!shared x, idx |
|
75 %! [x, idx] = sortrows ([1, 1; 1, 2; 3, 6; 2, 7], [1, -2]); |
|
76 %!assert (x, [1, 2; 1, 1; 2, 7; 3, 6]); |
|
77 %!assert (idx, [2; 1; 4; 3]); |