function X = randp(P,N, M)
%#codegen

% RANDP - pick random values with relative probability
%
%     R = RANDP(PROB,N,M) returns integers in the range from 1 to
%     NUMEL(PROB) with a relative probability, so that the value X is
%     present approximately (PROB(X)./sum(PROB)) times in the matrix R.
%
%     All values of PROB should be equal to or larger than 0.



X = rand(N,M);
P = P(:) ;
assert(all(P>=0));
[~,X] = histc(X,[0 ; cumsum(P(:))] ./ sum(P)) ;

end
