Section: Random Number Generation
[0,1)
.
Two seperate syntaxes are possible. The first syntax specifies the array
dimensions as a sequence of scalar dimensions:
y = rand(d1,d2,...,dn).
The resulting array has the given dimensions, and is filled with
random numbers. The type of y
is double
, a 64-bit floating
point array. To get arrays of other types, use the typecast
functions.
The second syntax specifies the array dimensions as a vector,
where each element in the vector specifies a dimension length:
y = rand([d1,d2,...,dn]).
This syntax is more convenient for calling rand
using a
variable for the argument.
Finally, rand
supports two additional forms that allow
you to manipulate the state of the random number generator.
The first retrieves the state
y = rand('state')
which is a 625 length integer vector. The second form sets the state
rand('state',y)
or alternately, you can reset the random number generator with
rand('state',0)
rand
function.
--> rand(2,2,2) ans = <double> - size: [2 2 2] (:,:,1) = Columns 1 to 2 0.34781131824756051 0.53132887383000482 0.02764473155572167 0.99580448434567814 (:,:,2) = Columns 1 to 2 0.20792435029277934 0.75968119672921053 0.49210936348492584 0.33647929575280000
The second example demonstrates the second form of the rand
function.
--> rand([2,2,2]) ans = <double> - size: [2 2 2] (:,:,1) = Columns 1 to 2 0.86696050128726199 0.21740218080680240 0.27140169990196550 0.68970886822238253 (:,:,2) = Columns 1 to 2 0.23048304877176773 0.38978704519267782 0.17207596813829429 0.95446606830622471
The third example computes the mean and variance of a large number of uniform random numbers. Recall that the mean should be 1/2
, and the variance should be 1/12 ~ 0.083
.
--> x = rand(1,10000); --> mean(x) ans = <double> - size: [1 1] 0.5023477828209344 --> var(x) ans = <double> - size: [1 1] 0.08398086618909606
Now, we use the state manipulation functions of rand
to exactly reproduce
a random sequence. Note that unlike using seed
, we can exactly control where
the random number generator starts by saving the state.
--> rand('state',0) % restores us to startup conditions --> a = rand(1,3) % random sequence 1 a = <double> - size: [1 3] Columns 1 to 3 0.375948080123701178 0.018339481363303323 0.913417011246358990 --> b = rand('state'); % capture the state vector --> c = rand(1,3) % random sequence 2 c = <double> - size: [1 3] Columns 1 to 3 0.35798651897090505 0.76039915395710944 0.80767825652147507 --> rand('state',b); % restart the random generator so... --> c = rand(1,3) % we get random sequence 2 again c = <double> - size: [1 3] Columns 1 to 3 0.35798651897090505 0.76039915395710944 0.80767825652147507