RAND Uniform Random Number Generator

Section: Random Number Generation

Usage

Creates an array of pseudo-random numbers of the specified size. The numbers are uniformly distributed on [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)

Example

The following example demonstrates an example of using the first form of the rand function.
--> rand(2,2,2)

ans = 

(:,:,1) = 
    0.3478    0.5313 
    0.0276    0.9958 

(:,:,2) = 
    0.2079    0.7597 
    0.4921    0.3365 

The second example demonstrates the second form of the rand function.

--> rand([2,2,2])

ans = 

(:,:,1) = 
    0.8670    0.2174 
    0.2714    0.6897 

(:,:,2) = 
    0.2305    0.3898 
    0.1721    0.9545 

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 = 
    0.5023 

--> var(x)

ans = 
    0.0840 

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 = 
    0.3759    0.0183    0.9134 

--> b = rand('state'); % capture the state vector
--> c = rand(1,3)      % random sequence 2  

c = 
    0.3580    0.7604    0.8077 

--> rand('state',b);   % restart the random generator so...
--> c = rand(1,3)      % we get random sequence 2 again

c = 
    0.3580    0.7604    0.8077