%------------------------------------------------------------------------- %------------------------------------------------------------------------- % Drawing from densities %------------------------------------------------------------------------- %------------------------------------------------------------------------- clear all; clc; %---------- # 1: Drawing from uniform and St.Normal %------------ N=50; x.uniform=unifrnd(0,1,N,1); %generate the sequence of random standard uniform variables x.stand_normal=randn(N,1); %generate the sequence of random standard normal variables %---------- Plotting the histogram -------------------------------------- %hist(x.uniform); %lines are commented since we'll get all %hist(x.stand_normal); %the hisograms later on in a single graph %---------- # 2: Generating Normal(2,9) ------------------------- mu=2; sigma_sq=9; x.normal=mu + sqrt(sigma_sq)*x.stand_normal; %hist(x.normal); %---------- # 3: Generating Log-Normal(-1,0.25) ------------------ mu=-1; sigma_sq=0.25; x.lognormal=exp(mu+sqrt(sigma_sq)*x.stand_normal); %hist(x.lognormal); %---------- # 4: Extreme value ---------------------------------- x.extreme=-log(-log(x.uniform)) %hist(x.extreme); %---------- # 5: Truncated Normal with strictly negative values -------- %---------- Method i: ------------------------ mu=2; sigma_sq=9; x.uniform=unifrnd(0,1,N,1); x.truncated=norminv(normcdf(0,mu,sqrt(sigma_sq))*x.uniform); %hist(x.truncated); %---------- Method ii: Accept-Reject technique ------------------------ % works much slower than previous and given just for the sake of completeness x.truncated1=zeros(N,1); tries=100000; %max number of tries to draw from N(2,9) k=1; for i=1:tries; e=mu + sqrt(sigma_sq)*randn; if e<0 x.truncated1(k)=e; k=k+1; if k>N break end; end; end; if k