Random Signals for Engineers using MATLAB and Mathcad Copyright 1999 Springer Verlag NY Example 3.8 Random Number Sequences with Arbitrary Distributions In this example we will use the histogram function to create a discrete random number sequence with and arbitrary distribution. Let us assume that there exists a probability outcome pair that we would like to match val=[1 2 3 4] Probs=[.2 .1 .45 .25] val = 1 2 Probs = 0.2000 3 0.1000 4 0.4500 0.2500 We set up a vector of intervals that are equal to the probabilities we would like to match. The cumsum is a Matlab implementation of Equation 3.5-6 and the center points are chosen to use the histogram function to determine the number of times random variable falls in each bin. function y= center_bin(intv) % computes the center bin for a histogram n=length(intv)-1; d= (intv(2)-intv(1))/2; y(1)= intv(1)-d for i=1:n y(i+1) = intv(i)+d d=intv(i+1)-y(i+1) end intervals=cumsum(Probs) x=center_bin(intervals) intervals = 0.2000 x = 0.1500 0.3000 0.7500 1.0000 0.2500 0.3500 1.1500 Now draw random numbers uniformly distributed between 0 and 1. If a number falls in the first interval, interpret it as outcome 1, in the second interval as outcome 2, and so on. r is a random number sequence from a uniform distribution r=[0 .19 .59 .35 .82 .17 .71 .3] r = Columns 1 through 7 0 0.1900 Column 8 0.3000 0.5900 0.3500 0.8200 0.1700 0.7100 The histogram function counts the number of Ri in each interval 0-0.2, 0.2-0.3, 0.3-0.75 and 0.75-1. R is a column vector for i=1:length(r) n=hist(r(i),x); m(i)=val*n'; end The histogram function forms a vector that represents the interval that the first column number of r falls. The dot product by column of m and the val vector assigns the proper outcome to the r i as 1 2 3 4. The vector m now contains the results of N trials of the experiment. m m = 1 1 3 3 4 1 3 2 Now let us repeat the experiment with a larger sample and indeed verify by the use of the counting function that the sample follows the original distribution. N=500; r=rand(1,N); for i=1:length(r) n=hist(r(i),x); m(i)=val*n'; end We use the histogram function to count the number of 1’s, 2’s etc. in the m vector. Using the vector operator of Matlab we divide each count by N to determine the relative frequency below and compare this to the original probability definition. v=hist(m,val)./N v = 0.1800 0.0900 0.4940 0.2360 0.4500 0.2500 Probs = [.2 .1 .45 .25] Probs = 0.2000 0.1000 For N = 500 there is good agreement as we increase N we expect the agreement to improve.