function T = sample_discr_same_length(P)

% sample m numbers from a different distribution given by the row of P
% all draws can be from 1 to p 
% INPUT: P is mxp
% OUTPUT: T is mx1 

% Copyright (c) 2013-2018, Francesco Corsello, All Rights Reserved.

[m,p]=size(P);
%normalize  the distributions in P

normconst=sum(P,2);
Pnorm=[zeros(m,1) P]./repmat(normconst,1,p+1);

idNotExistingPnorm=any(isnan(Pnorm),2);

if sum(idNotExistingPnorm)>0
    Pnorm(idNotExistingPnorm,:)=0;
end

%create cumulative distributions
Pcum=cumsum(Pnorm,2);

%create random matrix
R=rand(m,1);


reprand=repmat(R,1,p+1)  ;
T=p-sum(reprand<Pcum,2)+1;
