wolffd@0: function M = sample_discrete(prob, r, c) wolffd@0: % SAMPLE_DISCRETE Like the built in 'rand', except we draw from a non-uniform discrete distrib. wolffd@0: % M = sample_discrete(prob, r, c) wolffd@0: % wolffd@0: % Example: sample_discrete([0.8 0.2], 1, 10) generates a row vector of 10 random integers from {1,2}, wolffd@0: % where the prob. of being 1 is 0.8 and the prob of being 2 is 0.2. wolffd@0: wolffd@0: n = length(prob); wolffd@0: wolffd@0: if nargin == 1 wolffd@0: r = 1; c = 1; wolffd@0: elseif nargin == 2 wolffd@0: c == r; wolffd@0: end wolffd@0: wolffd@0: R = rand(r, c); wolffd@0: M = ones(r, c); wolffd@0: cumprob = cumsum(prob(:)); wolffd@0: wolffd@0: if n < r*c wolffd@0: for i = 1:n-1 wolffd@0: M = M + (R > cumprob(i)); wolffd@0: end wolffd@0: else wolffd@0: % loop over the smaller index - can be much faster if length(prob) >> r*c wolffd@0: cumprob2 = cumprob(1:end-1); wolffd@0: for i=1:r wolffd@0: for j=1:c wolffd@0: M(i,j) = sum(R(i,j) > cumprob2)+1; wolffd@0: end wolffd@0: end wolffd@0: end wolffd@0: wolffd@0: wolffd@0: % Slower, even though vectorized wolffd@0: %cumprob = reshape(cumsum([0 prob(1:end-1)]), [1 1 n]); wolffd@0: %M = sum(R(:,:,ones(n,1)) > cumprob(ones(r,1),ones(c,1),:), 3); wolffd@0: wolffd@0: % convert using a binning algorithm wolffd@0: %M=bindex(R,cumprob);