annotate toolboxes/FullBNT-1.0.7/KPMstats/multirnd.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 r = multirnd(theta,k)
wolffd@0 2 %MULTIRND - Random vector from multinomial distribution.
wolffd@0 3 % r = multirnd(theta,k) returns a vector randomly selected
wolffd@0 4 % from the multinomial distribution with parameter vector
wolffd@0 5 % theta, and count k (i.e. sum(r) = k).
wolffd@0 6 %
wolffd@0 7 % Note: if k is unspecified, then it is assumed k=1.
wolffd@0 8 %
wolffd@0 9 % Author: David Ross
wolffd@0 10 %
wolffd@0 11
wolffd@0 12 %--------------------------------------------------------
wolffd@0 13 % Check the arguments.
wolffd@0 14 %--------------------------------------------------------
wolffd@0 15 error(nargchk(1,2,nargin));
wolffd@0 16
wolffd@0 17 % make sure theta is a vector
wolffd@0 18 if ndims(theta) > 2 | all(size(theta) > 1)
wolffd@0 19 error('theta must be a vector');
wolffd@0 20 end
wolffd@0 21
wolffd@0 22 % if theta is a row vector, convert it to a column vector
wolffd@0 23 if size(theta,1) == 1
wolffd@0 24 theta = theta';
wolffd@0 25 end
wolffd@0 26
wolffd@0 27 % make sure k is a scalar?
wolffd@0 28
wolffd@0 29 % if the number of samples has not been provided, set
wolffd@0 30 % it to one
wolffd@0 31 if nargin == 1
wolffd@0 32 k = 1;
wolffd@0 33 end
wolffd@0 34
wolffd@0 35
wolffd@0 36 %--------------------------------------------------------
wolffd@0 37 % Main...
wolffd@0 38 %--------------------------------------------------------
wolffd@0 39 n = length(theta);
wolffd@0 40 theta_cdf = cumsum(theta);
wolffd@0 41
wolffd@0 42 r = zeros(n,1);
wolffd@0 43 random_vals = rand(k,1);
wolffd@0 44
wolffd@0 45 for j = 1:k
wolffd@0 46 index = min(find(random_vals(j) <= theta_cdf));
wolffd@0 47 r(index) = r(index) + 1;
wolffd@0 48 end