1 ## Copyright (C) 1995-2012 Kurt Hornik
3 ## This file is part of Octave.
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
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
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.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {} ranks (@var{x}, @var{dim})
21 ## Return the ranks of @var{x} along the first non-singleton dimension
22 ## adjusted for ties. If the optional argument @var{dim} is
23 ## given, operate along this dimension.
24 ## @seealso{spearman, kendall}
27 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
28 ## Description: Compute ranks
30 ## This code was rather ugly, since it didn't use sort due to the
31 ## fact of how to deal with ties. Now it does use sort and its
32 ## even uglier!!! At least it handles NDArrays..
34 function y = ranks (x, dim)
36 if (nargin != 1 && nargin != 2)
40 if (! (isnumeric (x) || islogical (x)))
41 error ("ranks: X must be a numeric vector or matrix");
47 ## Find the first non-singleton dimension.
48 (dim = find (sz > 1, 1)) || (dim = 1);
50 if (!(isscalar (dim) && dim == fix (dim))
51 || !(1 <= dim && dim <= nd))
52 error ("ranks: DIM must be an integer and a valid dimension");
59 ## The algorithm works only on dim = 1, so permute if necesary.
64 x = permute (x, perm);
67 infvec = -Inf ([1, sz(2 : end)]);
69 eq_el = find (diff ([xs; infvec]) == 0);
71 [eq_el, y] = sort (xi);
73 runs = setdiff (eq_el, eq_el+1);
74 len = diff (find (diff ([Inf; eq_el; -Inf]) != 1)) + 1;
75 [eq_el, y] = sort (xi);
76 for i = 1 : length(runs)
77 y (xi (runs (i) + [0:(len(i)-1)]) + floor (runs (i) ./ sz(1))
78 * sz(1)) = eq_el(runs(i)) + (len(i) - 1) / 2;
82 y = permute (y, perm);
89 %!assert(ranks (1:2:10), 1:5);
90 %!assert(ranks (10:-2:1), 5:-1:1);
91 %!assert(ranks ([2, 1, 2, 4]), [2.5, 1, 2.5, 4]);
92 %!assert(ranks (ones(1, 5)), 3*ones(1, 5));
93 %!assert(ranks (1e6*ones(1, 5)), 3*ones(1, 5));
94 %!assert(ranks (rand (1, 5), 1), ones(1, 5));
96 %% Test input validation
98 %!error ranks (1, 2, 3)
99 %!error ranks ({1, 2})
100 %!error ranks (['A'; 'B'])
101 %!error ranks (1, 1.5)