changelog shortlog tags changeset files revisions annotate raw

scripts/statistics/base/ranks.m

changeset 10289: 4b124317dc38
parent:eb63fbe60fab
author: John W. Eaton <jwe@octave.org>
date: Tue Feb 09 20:58:55 2010 -0500 (29 minutes ago)
permissions: -rw-r--r--
description: base_properties::set_children: account for hidden children
1## Copyright (C) 1995, 1996, 1997, 1998, 2000, 2002, 2004, 2005, 2006,
2## 2007, 2008, 2009 Kurt Hornik
3##
4## This file is part of Octave.
5##
6## Octave is free software; you can redistribute it and/or modify it
7## under the terms of the GNU General Public License as published by
8## the Free Software Foundation; either version 3 of the License, or (at
9## your option) any later version.
10##
11## Octave is distributed in the hope that it will be useful, but
12## WITHOUT ANY WARRANTY; without even the implied warranty of
13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14## General Public License for more details.
15##
16## You should have received a copy of the GNU General Public License
17## along with Octave; see the file COPYING. If not, see
18## <http://www.gnu.org/licenses/>.
19
20## -*- texinfo -*-
21## @deftypefn {Function File} {} ranks (@var{x}, @var{dim})
22## Return the ranks of @var{x} along the first non-singleton dimension
23## adjust for ties. If the optional argument @var{dim} is
24## given, operate along this dimension.
25## @end deftypefn
26
27## Author: KH <Kurt.Hornik@wu-wien.ac.at>
28## Description: Compute ranks
29
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..
33
34function y = ranks (x, dim)
35
36 if (nargin != 1 && nargin != 2)
37 print_usage ();
38 endif
39
40 nd = ndims (x);
41 sz = size (x);
42 if (nargin != 2)
43 ## Find the first non-singleton dimension.
44 dim = 1;
45 while (dim < nd + 1 && sz(dim) == 1)
46 dim = dim + 1;
47 endwhile
48 if (dim > nd)
49 dim = 1;
50 endif
51 else
52 if (! (isscalar (dim) && dim == round (dim))
53 && dim > 0
54 && dim < (nd + 1))
55 error ("ranks: dim must be an integer and valid dimension");
56 endif
57 endif
58
59 if (sz(dim) == 1)
60 y = ones(sz);
61 else
62 ## The algorithm works only on dim = 1, so permute if necesary.
63 if (dim != 1)
64 perm = [1 : nd];
65 perm(1) = dim;
66 perm(dim) = 1;
67 x = permute (x, perm);
68 endif
69 sz = size (x);
70 infvec = -Inf * ones ([1, sz(2 : end)]);
71 [xs, xi] = sort (x);
72 eq_el = find (diff ([xs; infvec]) == 0);
73 if (isempty (eq_el))
74 [eq_el, y] = sort (xi);
75 else
76 runs = complement (eq_el+1, eq_el);
77 len = diff (find (diff ([Inf; eq_el; -Inf]) != 1)) + 1;
78 [eq_el, y] = sort (xi);
79 for i = 1 : length(runs)
80 y (xi (runs (i) + [0:(len(i)-1)]) + floor (runs (i) ./ sz(1))
81 * sz(1)) = eq_el(runs(i)) + (len(i) - 1) / 2;
82 endfor
83 endif
84 if (dim != 1)
85 y = permute (y, perm);
86 endif
87 endif
88
89endfunction