function T = discrete(P)
% This function generates a
% random variable equal to k w.p. P(k)/sum(P).
 % Here, P = [P(1), P(2), ..., P(K)] where
% the P(k) are nonnegative.
Pnorm=[0 P]/sum(P);
Pcum=cumsum(Pnorm);
R=rand(1);
[~,T] = histc(R,Pcum);