Generating Pseudo-Random Numbers in Matlab Or, How To Use Rand and Randn
Generating Pseudo-Random Numbers in Matlab Or, How To Use Rand and Randn
or,
How to use rand and randn
Gerald W. Recktenwald
Department of Mechanical Engineering
Portland State University
[email protected]
A = rand(m,n)
• A is a matrix with m rows and n columns.
• Elements of A are approximately a uniform random distribution on [0, 1].
B = randn(m,n)
• B is a matrix with m rows and n columns.
• Elements of B are approximately a normal distribution with mean of 0 and standard
deviation of 1.
The probability density for the (ideal) normal distribution is
!
2
1 (x − µ)
p(x) = √ exp −
2σ 2π 2σ 2
x = rand(500,1); x = randn(500,1);
histogram(x); histogram(x);
Given a vector x
xmax − xmin
∆x =
n
Histograms tell us how the values in x are distributed over the range of x.
Left Right
edge edge Counts
-3.0 -2.5 2
-2.5 -2.0 4 97 values between
0 and 0.5
-2.0 -1.5 24 bin [0, 0.5)
-1.5 -1.0 62
-1.0 -0.5 71 62 values between
–1.5 and –1.0
-0.5 0.0 87
0.0 0.5 97
bin [–1.5, –1.0)
0.5 1.0 69
1.0 1.5 48
1.5 2.0 21
2.0 2.5 9
2.5 3.0 5
3.0 3.5 1
Especially for small sample sizes, the distributions from randn will not look like a classical
normal distribution. That’s OK. The output should be random, not uniformly normal.
Here are six consecutive distributions created with 30 samples from randn
Use this:
x = xbar + sig*randn(n,1)
xbar is the desired mean and sig is the desired standard deviation.
The seed values use to initialize the pseudo-random number generators are reused at the
start of each Matlab session, unless you explicitly tell Matlab not to start at the same
values.
The sequence of random values generated by rand and randn repeats unless you issue the
rng(’shuffle’)