1 ## Copyright (C) 2012 Rik Wehbring
2 ## Copyright (C) 2010-2012 David Bateman
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_cdf (@var{x}, @var{v}, @var{p})
22 ## For each element of @var{x}, compute the cumulative distribution
23 ## function (CDF) at @var{x} of a univariate discrete distribution which
24 ## assumes the values in @var{v} with probabilities @var{p}.
27 function cdf = discrete_cdf (x, v, p)
34 error ("discrete_cdf: V must be a vector");
35 elseif (any (isnan (v)))
36 error ("discrete_cdf: V must not have any NaN elements");
37 elseif (! isvector (p) || (length (p) != length (v)))
38 error ("discrete_cdf: P must be a vector with length (V) elements");
39 elseif (! (all (p >= 0) && any (p)))
40 error ("discrete_cdf: P must be a nonzero, non-negative vector");
43 p = p(:) / sum (p); # Reshape and normalize probability vector
45 if (isa (x, "single") || isa (v, "single") || isa (p, "single"));
46 cdf = NaN (size (x), "single");
53 cdf(k) = [0 ; cumsum(p(vi))](lookup (vs, x(k)) + 1);
59 %! x = [-1 0.1 1.1 1.9 3];
61 %! p = 1/length(v) * ones(1, length(v));
62 %! y = [0 0.1 0.6 1 1];
63 %!assert(discrete_cdf ([x, NaN], v, p), [y, NaN], eps);
65 %% Test class of input preserved
66 %!assert(discrete_cdf (single([x, NaN]), v, p), single([y, NaN]), 2*eps("single"));
67 %!assert(discrete_cdf ([x, NaN], single(v), p), single([y, NaN]), 2*eps("single"));
68 %!assert(discrete_cdf ([x, NaN], v, single(p)), single([y, NaN]), 2*eps("single"));
70 %% Test input validation
71 %!error discrete_cdf ()
72 %!error discrete_cdf (1)
73 %!error discrete_cdf (1,2)
74 %!error discrete_cdf (1,2,3,4)
75 %!error discrete_cdf (1, ones(2), ones(2,1))
76 %!error discrete_cdf (1, [1 ; NaN], ones(2,1))
77 %!error discrete_cdf (1, ones(2,1), ones(1,1))
78 %!error discrete_cdf (1, ones(2,1), [1 -1])
79 %!error discrete_cdf (1, ones(2,1), [1 NaN])
80 %!error discrete_cdf (1, ones(2,1), [0 0])