function out = mnldraws (pmat)
%
%
% PURPOSE: returns random draws from the multinomial
% MUCH faster than Matlab's internal mnlrnd function, produces exact same
% output
%---------------------------------------------------
% INPUTS: 
% where: pmat = n by G matrix of bin probabilities
% each row of pmat includes the bin probabilities for a separate
% observation
% all bin probabilities must sum to one
% so the smallest dimension of pmat is 1 x 2
%---------------------------------------------------
% OUTPUT:
% a n by G matrix of binary indicators, one "1" and G-1 zeros for each row     
%
%
% written by:
% Klaus Moeltner
% Virginia Tech

n=size(pmat,1); %#observations
G=size(pmat,2); %#bins

u=rand(n,1);
rr=repmat(u,1,G);
int1=cumsum(pmat,2);
int2=rr-int1;
int3=int2<0; %logical array
%now find first occurrence of 1 in each row
[M c]=max(int3 >0,[],2); %n by 1 vector indicating correct bin

Zmat = zeros(n, G);
Zmat(sub2ind(size(Zmat), 1:numel(c), c')) = 1;
out=Zmat;






