Generating Random Numbers in Matlab

Matlab → BasicsArrays → Statistical Functions → Random Numbers

Simulations of many physical, financial, and engineering applications frequently require using a number (or a set of numbers) with a random value. Matlab has three commands for this:

1. rand
generates uniformly distributed random numbers with values between 0 and 1. That is, in the interval (0,1), not including 0 and 1.

2. randi
uniformly distributed random integer.

3. randn
normally distributed random number with mean 0 and standard deviation of 1.

Figure: Matlab Command Window

Random Numbers: Examples
A uniformly distributed random number between 0 and 1.

>> rand
ans =
0.1270

>> rand
ans =
0.9134

>> rand
ans =
0.6324

Two rows and three columns of random numbers.
>> rand(2,3)
ans =
0.0975 0.5469 0.9649
0.2785 0.9575 0.1576

One row and two columns of random numbers.
>> rand(1,2)
ans =
0.9706 0.9572

Uniformly distributed random numbers in the interval (a,b)
We can generate uniformly distributed random numbers between a and b using the formula

(b-a)*rand+a

Consider the following two examples,

1. Generate 1 row and 3 columns of random numbers between 15 and 20.

>> 5*rand(1,3)+15
ans =
16.3190 15.7277 15.6803

2. Generate 2 rows and 5 columns of random numbers between 10 and 20.

>> 10*rand(2,5)+10
ans =
14.8538 11.4189 19.1574 19.5949 10.3571
18.0028 14.2176 17.9221 16.5574 18.4913

Random Integers

>> randi(10)
ans =
6

Random integer in the interval [1,10]

>> randi(15)
ans =
11

Random integer in the interval [1,15]

>> randi(8,3)
ans =
7 6 1
6 2 3
4 6 1

A 3×3 matrix in the interval [1,8]

>> randi(8,2,3)
ans =
1 6 8
7 3 1

A 2×3 matrix in the interval [1,8]

>> A=randi([-10 10],3,4)
A =
-1 6 -1 5
-2 -7 3 -5
6 0 4 4

A 3×4 matrix of random integers in the interval [-10,10]

Normally distributed random number
A normally distributed random number with mean 0 and standard deviation of 1.

>> randn
ans =
0.6007

>> randn
ans =
-1.2141

>> randn
ans =
-1.1135

Now, A 2×3 matrix of normally distributed random numbers with mean 0 and standard deviation 1.

>> randn(2,3)
ans =
-0.8045 0.8351 0.2157
0.6966 -0.2437 -1.1658

Normally distributed random number with mean m and standard deviation s
We can generate normally distributed random number with mean m and standard deviation s in Matlab using the formula

s*randn+m

For example, we can generate a 2×3 matrix of normally distributed random numbers with mean 50 and standard deviation of 4 as,

>> 4*randn(2,3)+50
ans =
50.4004 51.2141 51.9599
47.8219 47.5987 52.9575

Integers of normally distributed random numbers
Normally distributed random integers can be obtained by using the round function. For example, the following Matlab code generates a 2×4 matrix of normally distributed random integers with mean 50 and standard deviation 4.

>> round(4*randn(2,4)+50)
ans =
57 41 55 54
49 47 46 50