1## Copyright (C) 2012 Rik Wehbring
2## Copyright (C) 2007-2016 David Bateman
3##
4## This program is free software: you can redistribute it and/or
5## modify it under the terms of the GNU General Public License as
6## published by the Free Software Foundation, either version 3 of the
7## License, or (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful, but
10## WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12## General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; see the file COPYING.  If not, see
16## <http://www.gnu.org/licenses/>.
17
18## -*- texinfo -*-
19## @deftypefn {} {} unidinv (@var{x}, @var{n})
20## For each element of @var{x}, compute the quantile (the inverse of the CDF)
21## at @var{x} of the discrete uniform distribution which assumes
22## the integer values 1--@var{n} with equal probability.
23## @end deftypefn
24
25function inv = unidinv (x, n)
26
27  if (nargin != 2)
28    print_usage ();
29  endif
30
31  if (! isscalar (n))
32    [retval, x, n] = common_size (x, n);
33    if (retval > 0)
34      error ("unidcdf: X and N must be of common size or scalars");
35    endif
36  endif
37
38  if (iscomplex (x) || iscomplex (n))
39    error ("unidinv: X and N must not be complex");
40  endif
41
42  if (isa (x, "single") || isa (n, "single"))
43    inv = NaN (size (x), "single");
44  else
45    inv = NaN (size (x));
46  endif
47
48  ## For Matlab compatibility, unidinv(0) = NaN
49  k = (x > 0) & (x <= 1) & (n > 0 & n == fix (n));
50  if (isscalar (n))
51    inv(k) = floor (x(k) * n);
52  else
53    inv(k) = floor (x(k) .* n(k));
54  endif
55
56endfunction
57
58
59%!shared x
60%! x = [-1 0 0.5 1 2];
61%!assert (unidinv (x, 10*ones (1,5)), [NaN NaN 5 10 NaN], eps)
62%!assert (unidinv (x, 10), [NaN NaN 5 10 NaN], eps)
63%!assert (unidinv (x, 10*[0 1 NaN 1 1]), [NaN NaN NaN 10 NaN], eps)
64%!assert (unidinv ([x(1:2) NaN x(4:5)], 10), [NaN NaN NaN 10 NaN], eps)
65
66## Test class of input preserved
67%!assert (unidinv ([x, NaN], 10), [NaN NaN 5 10 NaN NaN], eps)
68%!assert (unidinv (single ([x, NaN]), 10), single ([NaN NaN 5 10 NaN NaN]), eps)
69%!assert (unidinv ([x, NaN], single (10)), single ([NaN NaN 5 10 NaN NaN]), eps)
70
71## Test input validation
72%!error unidinv ()
73%!error unidinv (1)
74%!error unidinv (1,2,3)
75%!error unidinv (ones (3), ones (2))
76%!error unidinv (ones (2), ones (3))
77%!error unidinv (i, 2)
78%!error unidinv (2, i)
79