]> Creatis software - CreaPhase.git/blob - octave_packages/m/statistics/distributions/unidpdf.m
update packages
[CreaPhase.git] / octave_packages / m / statistics / distributions / unidpdf.m
1 ## Copyright (C) 2012 Rik Wehbring
2 ## Copyright (C) 2007-2012 David Bateman
3 ##
4 ## This file is part of Octave.
5 ##
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.
10 ##
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.
15 ##
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/>.
19
20 ## -*- texinfo -*-
21 ## @deftypefn {Function File} {} unidpdf (@var{x}, @var{n})
22 ## For each element of @var{x}, compute the probability density function
23 ## (PDF) at @var{x} of a discrete uniform distribution which assumes
24 ## the integer values 1--@var{n} with equal probability.
25 ##
26 ## Warning: The underlying implementation uses the double class and
27 ## will only be accurate for @var{n} @leq{} @code{bitmax} 
28 ## (@w{@math{2^{53} - 1}} on IEEE-754 compatible systems).
29 ## @end deftypefn
30
31 function pdf = unidpdf (x, n)
32
33   if (nargin != 2)
34     print_usage ();
35   endif
36
37   if (! isscalar (n))
38     [retval, x, n] = common_size (x, n);
39     if (retval > 0)
40       error ("unidpdf: X and N must be of common size or scalars");
41     endif
42   endif
43
44   if (iscomplex (x) || iscomplex (n))
45     error ("unidpdf: X and N must not be complex");
46   endif
47
48   if (isa (x, "single") || isa (n, "single"))
49     pdf = zeros (size (x), "single");
50   else
51     pdf = zeros (size (x));
52   endif
53
54   k = isnan (x) | ! (n > 0 & n == fix (n));
55   pdf(k) = NaN;
56
57   k = !k & (x >= 1) & (x <= n) & (x == fix (x));
58   if (isscalar (n))
59     pdf(k) = 1 / n;
60   else
61     pdf(k) = 1 ./ n(k);
62   endif
63
64 endfunction
65
66
67 %!shared x,y
68 %! x = [-1 0 1 2 10 11];
69 %! y = [0 0 0.1 0.1 0.1 0];
70 %!assert(unidpdf (x, 10*ones(1,6)), y);
71 %!assert(unidpdf (x, 10), y);
72 %!assert(unidpdf (x, 10*[0 NaN 1 1 1 1]), [NaN NaN y(3:6)]);
73 %!assert(unidpdf ([x, NaN], 10), [y, NaN]);
74
75 %% Test class of input preserved
76 %!assert(unidpdf (single([x, NaN]), 10), single([y, NaN]));
77 %!assert(unidpdf ([x, NaN], single(10)), single([y, NaN]));
78
79 %% Test input validation
80 %!error unidpdf ()
81 %!error unidpdf (1)
82 %!error unidpdf (1,2,3)
83 %!error unidpdf (ones(3),ones(2))
84 %!error unidpdf (ones(2),ones(3))
85 %!error unidpdf (i, 2)
86 %!error unidpdf (2, i)
87