Mercurial > hg > camir-aes2014
comparison toolboxes/FullBNT-1.0.7/KPMstats/sample_discrete.m @ 0:e9a9cd732c1e tip
first hg version after svn
author | wolffd |
---|---|
date | Tue, 10 Feb 2015 15:05:51 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:e9a9cd732c1e |
---|---|
1 function M = sample_discrete(prob, r, c) | |
2 % SAMPLE_DISCRETE Like the built in 'rand', except we draw from a non-uniform discrete distrib. | |
3 % M = sample_discrete(prob, r, c) | |
4 % | |
5 % Example: sample_discrete([0.8 0.2], 1, 10) generates a row vector of 10 random integers from {1,2}, | |
6 % where the prob. of being 1 is 0.8 and the prob of being 2 is 0.2. | |
7 | |
8 n = length(prob); | |
9 | |
10 if nargin == 1 | |
11 r = 1; c = 1; | |
12 elseif nargin == 2 | |
13 c == r; | |
14 end | |
15 | |
16 R = rand(r, c); | |
17 M = ones(r, c); | |
18 cumprob = cumsum(prob(:)); | |
19 | |
20 if n < r*c | |
21 for i = 1:n-1 | |
22 M = M + (R > cumprob(i)); | |
23 end | |
24 else | |
25 % loop over the smaller index - can be much faster if length(prob) >> r*c | |
26 cumprob2 = cumprob(1:end-1); | |
27 for i=1:r | |
28 for j=1:c | |
29 M(i,j) = sum(R(i,j) > cumprob2)+1; | |
30 end | |
31 end | |
32 end | |
33 | |
34 | |
35 % Slower, even though vectorized | |
36 %cumprob = reshape(cumsum([0 prob(1:end-1)]), [1 1 n]); | |
37 %M = sum(R(:,:,ones(n,1)) > cumprob(ones(r,1),ones(c,1),:), 3); | |
38 | |
39 % convert using a binning algorithm | |
40 %M=bindex(R,cumprob); |