3191
|
1 ## Copyright (C) 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: discrete_rnd (N, V, P) |
|
18 ## |
|
19 ## Generate a random sample of size N from the univariate distribution |
|
20 ## which assumes the values in V with probabilities P. |
|
21 ## |
|
22 ## Currently, N must be a scalar. |
|
23 |
|
24 ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at> |
|
25 ## Description: Random deviates from a discrete distribution |
|
26 |
|
27 function rnd = discrete_rnd (N, V, P) |
|
28 |
|
29 if (nargin != 3) |
|
30 usage ("discrete_rnd (N, V, P)"); |
|
31 endif |
|
32 |
|
33 if !is_scalar (N) |
|
34 error ("discrete_rnd: N must be a scalar"); |
|
35 endif |
|
36 |
|
37 if (! is_vector (V)) |
|
38 error ("discrete_rnd: V must be a vector"); |
|
39 elseif (! is_vector (P) || (length (P) != length (V))) |
|
40 error ("discrete_rnd: P must be a vector with length (V) elements"); |
|
41 elseif (! (all (P >= 0) && any (P))) |
|
42 error ("discrete_rnd: P must be a nonzero, nonnegative vector"); |
|
43 endif |
|
44 |
|
45 u = rand (1, N); |
|
46 m = length (P); |
|
47 s = reshape (cumsum (P / sum (P)), m, 1); |
|
48 |
|
49 rnd = V (1 + sum ((s * ones (1, N)) <= ((ones (m, 1) * u)))); |
|
50 |
|
51 if (prefer_column_vectors) |
|
52 rnd = rnd'; |
|
53 endif |
|
54 |
|
55 endfunction |