Skip to Main Content Skip to Search
Product Documentation

rand - Uniformly distributed pseudorandom numbers

Syntax

r = rand(n)
r = rand(m,n)
r = rand([m,n])
r = rand(m,n,p,...)
r = rand([m,n,p,...])
r = rand
r = rand(size(A))
r = rand(..., 'double')
r = rand(..., 'single')

Description

r = rand(n) returns an n-by-n matrix containing pseudorandom values drawn from the standard uniform distribution on the open interval (0,1). r = rand(m,n) or r = rand([m,n]) returns an m-by-n matrix. r = rand(m,n,p,...) or r = rand([m,n,p,...]) returns an m-by-n-by-p-by-... array. r = rand returns a scalar. r = rand(size(A)) returns an array the same size as A.

r = rand(..., 'double') or r = rand(..., 'single') returns an array of uniform values of the specified class.

The sequence of numbers produced by rand is determined by the internal settings of the uniform random number generator that underlies rand, randi, and randn. You can control that shared random number generator using rng.

Examples

Example 1

Generate values from the uniform distribution on the interval [a, b]:

 r = a + (b-a).*rand(100,1);

Example 2

Use the randi function, instead of rand, to generate integer values from the uniform distribution on the set 1:100:

r = randi(100,1,5);

Example 3

Reset the random number generator used by rand, randi, and randn to its default startup settings, so that rand produces the same random numbers as if you restarted MATLAB:

rng('default')
rand(1,5)
ans =
    0.8147    0.9058    0.1270    0.9134    0.6324

Example 4

Save the settings for the random number generator used by rand, randi, and randn, generate 5 values from rand, restore the settings, and repeat those values:

s = rng;
u1 = rand(1,5)
u1 =
    0.0975    0.2785    0.5469    0.9575    0.9649

rng(s);
u2 = rand(1,5)
u2 =
    0.0975    0.2785    0.5469    0.9575    0.9649

u2 contains exactly the same values as u1.

Example 5

Reinitialize the random number generator used by rand, randi, and randn with a seed based on the current time. rand returns different values each time you do this. Note that it is usually not necessary to do this more than once per MATLAB session as it may affect the statistical properties of the random numbers MATLAB produces:

rng('shuffle');
rand(1,5);

See Also

@RandStream | rand (RandStream) | randi | randn | randperm | rng | sprand | sprandn

  


Free MATLAB Interactive Kit

Explore how to use MATLAB to make advancements in engineering and science.


Download free kit

Trials Available

Try the latest version of MATLAB and other MathWorks products.


Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS