1 ## Copyright (C) 2012 Rik Wehbring
2 ## Copyright (C) 1996-2012 Kurt Hornik
4 ## This file is part of Octave.
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.
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.
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/>.
21 ## @deftypefn {Function File} {} discrete_inv (@var{x}, @var{v}, @var{p})
22 ## For each element of @var{x}, compute the quantile (the inverse of
23 ## the CDF) at @var{x} of the univariate distribution which assumes the
24 ## values in @var{v} with probabilities @var{p}.
27 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
28 ## Description: Quantile function of a discrete distribution
30 function inv = discrete_inv (x, v, p)
37 error ("discrete_inv: V must be a vector");
38 elseif (! isvector (p) || (length (p) != length (v)))
39 error ("discrete_inv: P must be a vector with length (V) elements");
40 elseif (any (isnan (p)))
41 error ("discrete_rnd: P must not have any NaN elements");
42 elseif (! (all (p >= 0) && any (p)))
43 error ("discrete_inv: P must be a nonzero, non-negative vector");
46 if (isa (x, "single") || isa (v, "single") || isa (p, "single"));
47 inv = NaN (size (x), "single");
52 ## FIXME: This isn't elegant. But cumsum and lookup together produce
53 ## different results when called with a single or a double.
54 if (isa (p, "single"));
59 p = cumsum (p(idx)(:)) / sum (p); # Reshape and normalize probability vector
67 k = (x > 0) & (x < 1);
68 inv(k) = v(length (p) - lookup (sort (p, "descend"), x(k)) + 1);
74 %! x = [-1 0 0.1 0.5 1 2];
76 %! p = 1/length(v) * ones(1, length(v));
77 %! y = [NaN v(1) v(1) v(end/2) v(end) NaN];
78 %!assert(discrete_inv ([x, NaN], v, p), [y, NaN], eps);
80 %% Test class of input preserved
81 %!assert(discrete_inv (single([x, NaN]), v, p), single([y, NaN]), eps("single"));
82 %!assert(discrete_inv ([x, NaN], single(v), p), single([y, NaN]), eps("single"));
83 %!assert(discrete_inv ([x, NaN], v, single(p)), single([y, NaN]), eps("single"));
85 %% Test input validation
86 %!error discrete_inv ()
87 %!error discrete_inv (1)
88 %!error discrete_inv (1,2)
89 %!error discrete_inv (1,2,3,4)
90 %!error discrete_inv (1, ones(2), ones(2,1))
91 %!error discrete_inv (1, ones(2,1), ones(1,1))
92 %!error discrete_inv (1, ones(2,1), [1 NaN])
93 %!error discrete_inv (1, ones(2,1), [1 -1])
94 %!error discrete_inv (1, ones(2,1), [0 0])