Last change
on this file since 177 was
37,
checked in by (none), 15 years ago
|
Added original make3d
|
-
Property svn:executable set to
*
|
File size:
1.2 KB
|
Line | |
---|
1 | function x = sample(p, n) |
---|
2 | %SAMPLE Sample from categorical distribution. |
---|
3 | % X = SAMPLE(P,N) returns a row vector of N integers, sampled according to the |
---|
4 | % probability distribution P (an array of numbers >= 0, whose sum is > 0). |
---|
5 | % sum(P) does not have to be 1, but it must be > 0. |
---|
6 | % X(i) ranges 1 to length(P). |
---|
7 | |
---|
8 | % Written by Tom Minka |
---|
9 | % (c) Microsoft Corporation. All rights reserved. |
---|
10 | |
---|
11 | % Written by Min Sun July 25th |
---|
12 | % adapt case when p contain Inf entries |
---|
13 | |
---|
14 | if nargin < 2 |
---|
15 | n = 1; |
---|
16 | end |
---|
17 | |
---|
18 | % process case for Inf entries in p ============== |
---|
19 | DetX = find(p == Inf); |
---|
20 | RandList = find(p ~= Inf); |
---|
21 | RandList = RandList(:); |
---|
22 | p = p( RandList); |
---|
23 | % ================================================ |
---|
24 | |
---|
25 | if n < 10 |
---|
26 | cdf = cumsum(p(:)); |
---|
27 | if cdf(end) <= 0 |
---|
28 | error('distribution is all zeros'); |
---|
29 | end |
---|
30 | RandX = zeros(1,n); |
---|
31 | for i = 1:n |
---|
32 | RandX(i) = sum(cdf < rand*cdf(end)) + 1; |
---|
33 | end |
---|
34 | else |
---|
35 | % large n method |
---|
36 | p = p(:); |
---|
37 | p = p/sum(p); |
---|
38 | h = sample_hist(p,n); |
---|
39 | RandX = zeros(1,n); |
---|
40 | i = [0 cumsum(h)']; |
---|
41 | % set RandX = [1 1 1 1 2 2 3 3 3 ... ] |
---|
42 | for k = 1:length(h) |
---|
43 | RandX((i(k)+1):i(k+1)) = k; |
---|
44 | end |
---|
45 | RandX = RandX(randperm(n)); |
---|
46 | end |
---|
47 | |
---|
48 | % ================ |
---|
49 | x = [DetX(:); RandList(RandX)]; |
---|
50 | % ================ |
---|
Note: See
TracBrowser
for help on using the repository browser.