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_pdf (@var{x}, @var{v}, @var{p})
22 ## For each element of @var{x}, compute the probability density function
23 ## (PDF) at @var{x} of a univariate discrete distribution which assumes
24 ## the values in @var{v} with probabilities @var{p}.
27 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
28 ## Description: PDF of a discrete distribution
30 function pdf = discrete_pdf (x, v, p)
37 error ("discrete_pdf: V must be a vector");
38 elseif (any (isnan (v)))
39 error ("discrete_pdf: V must not have any NaN elements");
40 elseif (! isvector (p) || (length (p) != length (v)))
41 error ("discrete_pdf: P must be a vector with length (V) elements");
42 elseif (! (all (p >= 0) && any (p)))
43 error ("discrete_pdf: P must be a nonzero, non-negative vector");
46 ## Reshape and normalize probability vector. Values not in table get 0 prob.
47 p = [0 ; p(:)/sum(p)];
49 if (isa (x, "single") || isa (v, "single") || isa (p, "single"))
50 pdf = NaN (size (x), "single");
56 [vs, vi] = sort (v(:));
57 pdf(k) = p([0 ; vi](lookup (vs, x(k), 'm') + 1) + 1);
63 %! x = [-1 0.1 1.1 1.9 3];
65 %! p = 1/length(v) * ones(1, length(v));
66 %! y = [0 0.1 0.1 0.1 0];
67 %!assert(discrete_pdf ([x, NaN], v, p), [y, NaN], 5*eps);
69 %% Test class of input preserved
70 %!assert(discrete_pdf (single([x, NaN]), v, p), single([y, NaN]), 5*eps("single"));
71 %!assert(discrete_pdf ([x, NaN], single(v), p), single([y, NaN]), 5*eps("single"));
72 %!assert(discrete_pdf ([x, NaN], v, single(p)), single([y, NaN]), 5*eps("single"));
74 %% Test input validation
75 %!error discrete_pdf ()
76 %!error discrete_pdf (1)
77 %!error discrete_pdf (1,2)
78 %!error discrete_pdf (1,2,3,4)
79 %!error discrete_pdf (1, ones(2), ones(2,1))
80 %!error discrete_pdf (1, [1 ; NaN], ones(2,1))
81 %!error discrete_pdf (1, ones(2,1), ones(1,1))
82 %!error discrete_pdf (1, ones(2,1), [1 -1])
83 %!error discrete_pdf (1, ones(2,1), [1 NaN])
84 %!error discrete_pdf (1, ones(2,1), [0 0])