function X = di_rnd(m,n)

% Implements a random number generator
% from the discrete distribution given by:
%
% P(X = 0) = 0.3
% P(X = 1) = 0.2
% P(X = 2) = 0.5
%
% with a cdf given by:
%
% F(x) = 0, if x < 0
% F(x) = 0.3, if 0 <= x < 1
% F(x) = 0.5, if 1 <= x < 2
% F(x) = 1.0, if 2 <= x .
%
% using a discrete inversion method.

p = [0.3, 0.2, 0.5];

X = zeros(m, n);

for i = 1:m*n
    u = rand;
    if u <= p(1)
        X(i) = 0;
    elseif u <= sum(p(1:2))
        X(i) = 1;
    else
        X(i) = 2;
    end
end