Random Signals for Engineers using MATLAB and Mathcad Copyright 1999 Springer Verlag NY Example 3.9 Random Number Sequences with Continuous Distributions In this example we will generate a random sequence with an exponential distribution and show as we increase the number of samples in the sequence the mean and variance approaches the theoretical values for the exponential distribution. We will also show that the density distribution for the sequence approaches an exponential distribution. The transformation used to generate the sequence is exp l 1 log rand (1, N ) N=500; r=rand(N,1); The terms in the sequence are with = 0.2 lam=0.2; P=-1/lam*log(r); The mean as a function of n is defined. We have used the cumsum to sum the first n of the P terms. We plot this function with the theoretical value for the mean = 1 / for comparison. k=1:N; me=cumsum(P)'./k; tme=1/lam*ones(1,N); plot(k,me,k,tme) 6 5 4 3 2 1 0 0 50 100 150 200 250 300 350 400 450 500 A similar function is defined for the variance and plotted with the theoretical value m2=cumsum(P.^2)'./[1:N]; tm2=1/lam^2*ones(1,N); plot(k,m2-me.^2,k,tm2) 45 40 35 30 25 20 15 10 5 0 0 50 100 150 200 250 300 350 400 450 500 In order to generate a random sequence with an arbitrary distribution we need to have an analytical expression for the inverse of the cumulative distribution function. We may also use Matlab to invert a function or solve a nonlinear equation using solve. Let us define the inverse exponential function as syms x lambda u f=1-exp(-lambda*x); solve(f-u) ans = -log(1-u)/lambda We now generate a sequence using the inverse function and compare the analytical density function with the histogram. [w,v]=hist(P,40); fp=lam*exp(-lam*v); bar(v,w/N,0.2);hold on; plot(v,fp); hold off 0.2 0.18 0.16 0.14 0.12 0.1 0.08 0.06 0.04 0.02 0 0 5 10 15 20 25 30 35 40