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