Section 3.2 Random numbers and histograms
The command rand
produces random numbers uniformly distributed in the interval from 0 to 1. Without providing parameters, we get a single number: x = rand()
can make x equal to, for example, 0.8248. With parameters rand(m, n)
we get a random m×n matrix, meaning a matrix in which each entry is chosen randomly.
The command histogram(v, k)
displays a histograph of the data collected in vector v
using k
bins. This means that the interval from min(v)
to max(v)
is divided into k
equal subintervals, and the histogram counts how many data points fall in each subinterval. If the number of bins k
is not provided, Matlab will try to choose it itself. Usually we want 10-50 bins. For example,
v = rand(1, 10000); histogram(v, 20);
produces a histogram from 10000 random numbers. This will not be an interesting histogram since the numbers are uniformly distributed between 0 and 1.
For Octave users: histogram
may not be available in Octave, but hist
is. They are used in the same way, with one exception: to make a histogram of all entries of a matrix A
, one should use hist(A(:))
to flatten the matrix into a vector. With histogram
this flattening is automatic, so histogram(A)
works.
Example 3.2.1. Distribution of sums of random numbers.
Suppose we take 10 random numbers, uniformly distributed between 0 and 1, and compute their sum. Repeating this experiment 10000 times, we get 10000 such sums. Plot the histogram of these random sums.
A = rand(10, 10000); S = sum(A, 1); histogram(S, 30);
This histogram resembles a “bell curve” of normal distribution. The similarly grows stronger if we take sums of more numbers, and plot more random sums. This is the content of Central Limit Theorem in probability.