Daniel@0: function x = sample(p, n) Daniel@0: % SAMPLE Sample from categorical distribution. Daniel@0: % Returns a row vector of integers, sampled according to the probability Daniel@0: % distribution p. Daniel@0: % Uses the stick-breaking algorithm. Daniel@0: % Much faster algorithms are also possible. Daniel@0: Daniel@0: if nargin < 2 Daniel@0: n = 1; Daniel@0: end Daniel@0: Daniel@0: cdf = cumsum(p(:)); Daniel@0: for i = 1:n Daniel@0: x(i) = sum(cdf < rand) + 1; Daniel@0: end