annotate _FullBNT/KPMtools/sample_discrete.m @ 9:4ea6619cb3f5 tip

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