function M = sample_discrete_noC(prob, r, c)
% SAMPLE_DISCRETE Like the built in 'rand', except the elements of M are drawn from a discrete distrib.
% M = sample_discrete(prob, r, c)


if nargin == 1
  r = 1; c = 1;
elseif nargin == 2
  c == r;
end

prob = prob(:)'; % make row vector
cumprob = cumsum(prob);
n = length(prob);
if ~approxeq(cumprob(n), 1)
  error('distribution does not sum to 1');
end 

cumprob = [0 cumprob];
R = rand(r, c);
M = zeros(r,c);
for i=1:n
  M = M + (R>=cumprob(i) & R<=cumprob(i+1))*i;
end
