Page 93 - Computational Statistics Handbook with MATLAB
P. 93
80 Computational Statistics Handbook with MATLAB
the ability to generate uniform random variables very easily. However, we
have to caution the reader that the numbers generated by computers are
really pseudorandom because they are generated using a deterministic algo-
rithm. The techniques used to generate uniform random variables have been
widely studied in the literature, and it has been shown that some generators
have serious flaws [Gentle, 1998].
The basic MATLAB program has a function rand for generating uniform
random variables. There are several optional arguments, and we take a
moment to discuss them because they will be useful in simulation. The func-
tion rand with no arguments returns a single instance of the random variable
U. To get an m × n array of uniform variates, you can use the syntax
rand(m,n). A note of caution: if you use rand(n), then you get an n × n
matrix.
The sequence of random numbers that is generated in MATLAB depends
on the seed or the state of the generator. The state is reset to the default when
it starts up, so the same sequences of random variables are generated when-
ever you start MATLAB. This can sometimes be an advantage in situations
where we would like to obtain a specific random sample, as we illustrate in
the next example. If you call the function using rand('state',0), then
MATLAB resets the generator to the initial state. If you want to specify
another state, then use the syntax rand('state',j) to set the generator to
the j-th state. You can obtain the current state using S = rand(‘state’),
where S is a 35 element vector. To reset the state to this one, use
rand(‘state’,S).
It should be noted that random numbers that are uniformly distributed
over an interval a to b may be generated by a simple transformation, as fol-
lows
⋅
X = ( b – a) U + . a (4.1)
Example 4.1
In this example, we illustrate the use of MATLAB’s function rand.
% Obtain a vector of uniform random variables in (0,1).
x = rand(1,1000);
% Do a histogram to plot.
% First get the height of the bars.
[N,X] = hist(x,15);
% Use the bar function to plot.
bar(X,N,1,'w')
title('Histogram of Uniform Random Variables')
xlabel('X')
ylabel('Frequency')
The resulting histogram is shown in Figure 4.1. In some situations, the ana-
lyst might need to reproduce results from a simulation, say to verify a con-
© 2002 by Chapman & Hall/CRC