3191
|
1 ## Copyright (C) 1995, 1996, 1997 Kurt Hornik |
|
2 ## |
|
3 ## This program is free software; you can redistribute it and/or modify |
|
4 ## it under the terms of the GNU General Public License as published by |
|
5 ## the Free Software Foundation; either version 2, or (at your option) |
|
6 ## any later version. |
|
7 ## |
|
8 ## This program is distributed in the hope that it will be useful, but |
|
9 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
11 ## General Public License for more details. |
|
12 ## |
|
13 ## You should have received a copy of the GNU General Public License |
|
14 ## along with this file. If not, write to the Free Software Foundation, |
|
15 ## 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
|
16 |
|
17 ## usage: pascal_rnd (n, p [, r, c]) |
|
18 ## |
|
19 ## pascal_rnd (n, p) returns a matrix of random samples from the Pascal |
|
20 ## (negative binomial) distribution with parameters n and p. The size of |
|
21 ## the matrix is the common size of n and p. |
|
22 ## |
|
23 ## pascal_rnd (n, p, r, c) returns an r by c matrix of random samples |
|
24 ## from the Pascal distribution with parameters n and p. Both n and p |
|
25 ## must be scalar or of size r by c. |
|
26 |
|
27 ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at> |
|
28 ## Description: Random deviates from the Pascal distribution |
|
29 |
|
30 function rnd = pascal_rnd (n, p, r, c) |
|
31 |
|
32 if (nargin == 4) |
|
33 if ( !(is_scalar (r) && (r > 0) && (r == round (r))) ) |
|
34 error ("pascal_rnd: r must be a positive integer"); |
|
35 endif |
|
36 if ( !(is_scalar (c) && (c > 0) && (c == round (c))) ) |
|
37 error ("pascal_rnd: c must be a positive integer"); |
|
38 endif |
|
39 [retval, n, p] = common_size (n, p, zeros (r, c)); |
|
40 if (retval > 0) |
|
41 error (strcat("pascal_rnd: ", |
|
42 "n and p must be scalar or of size ", |
|
43 sprintf ("%d by %d", r, c))); |
|
44 endif |
|
45 elseif (nargin == 2) |
|
46 [retval, n, p] = common_size (n, p); |
|
47 if (retval > 0) |
|
48 error ("pascal_rnd: n and p must be of common size or scalar"); |
|
49 endif |
|
50 else |
|
51 usage ("pascal_rnd (n, p [, r, c])"); |
|
52 endif |
|
53 |
|
54 [r, c] = size (n); |
|
55 s = r * c; |
|
56 n = reshape (n, 1, s); |
|
57 p = reshape (p, 1, s); |
|
58 rnd = zeros (1, s); |
|
59 |
|
60 k = find (!(n > 0) | !(n < Inf) | !(n == round (n)) ... |
|
61 | !(p <= 0) | !(p >= 1)); |
|
62 if (any (k)) |
|
63 rnd(k) = NaN * ones (1, length (k)); |
|
64 endif |
|
65 |
|
66 k = find ((n > 0) & (n < Inf) & (n == round (n)) ... |
|
67 & (p >= 0) & (p <= 1)); |
|
68 if (any (k)) |
|
69 N = max (n(k)); |
|
70 L = length (k); |
|
71 tmp = floor (log (rand (N, L)) ./ (ones (N, 1) * log (1 - p(k)))); |
|
72 ind = (1 : N)' * ones (1, L); |
|
73 rnd(k) = sum (tmp .* (ind <= ones (N, 1) * n(k))); |
|
74 endif |
|
75 |
|
76 rnd = reshape (rnd, r, c); |
|
77 |
|
78 endfunction |