annotate toolboxes/FullBNT-1.0.7/KPMtools/sample_discrete.m @ 0:e9a9cd732c1e tip

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