1 ## Copyright (C) 1995-2012 Friedrich Leisch
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} {} run_count (@var{x}, @var{n})
21 ## @deftypefnx {Function File} {} run_count (@var{x}, @var{n}, @var{dim})
22 ## Count the upward runs along the first non-singleton dimension of
23 ## @var{x} of length 1, 2, @dots{}, @var{n}-1 and greater than or equal
26 ## If the optional argument @var{dim} is given then operate
27 ## along this dimension.
30 ## Author: FL <Friedrich.Leisch@ci.tuwien.ac.at>
31 ## Description: Count upward runs
33 function retval = run_count (x, n, dim)
35 if (nargin != 2 && nargin != 3)
39 if (! (isnumeric (x) || islogical (x)))
40 error ("run_count: X must be a numeric vector or matrix");
43 if (!(isscalar (n) && n == fix (n) && n > 0))
44 error ("run_count: N must be a positive integer");
50 ## Find the first non-singleton dimension.
51 (dim = find (sz > 1, 1)) || (dim = 1);
53 if (!(isscalar (dim) && dim == fix (dim))
54 || !(1 <= dim && dim <= nd))
55 error ("run_count: DIM must be an integer and a valid dimension");
59 ## Algorithm works on rows. Permute array if necessary, ipermute back at end
64 x = permute (x, perm);
73 tmp = zeros ([c + 1, sz(2 : end)]);
74 infvec = Inf ([1, sz(2 : end)]);
76 ind = find (diff ([infvec; x; -infvec]) < 0);
77 tmp(ind(2:end) - 1) = diff (ind);
84 retval(idx{:}) = sum (tmp == k);
87 retval(idx{:}) = sum (tmp >= n);
90 retval = ipermute (retval, perm);
96 %!assert(run_count (magic(3), 4), [1,0,1;1,0,1;0,1,0;0,0,0])
97 %!assert(run_count (magic(3), 4, 2), [1,0,1;1,0,1;0,1,0;0,0,0]')
98 %!assert(run_count (5:-1:1, 5), [5, 0, 0, 0, 0])
99 %!assert(run_count (ones(3), 4), [0,0,0;0,0,0;1,1,1;0,0,0])
101 %% Test input validation
103 %!error run_count (1)
104 %!error run_count (1, 2, 3, 4)
105 %!error run_count ({1, 2}, 3)
106 %!error run_count (['A'; 'A'; 'B'], 3)
107 %!error run_count (1:5, ones(2,2))
108 %!error run_count (1:5, 1.5)
109 %!error run_count (1:5, -2)
110 %!error run_count (1:5, 3, ones(2,2))
111 %!error run_count (1:5, 3, 1.5)
112 %!error run_count (1:5, 3, 0)