Skip to content

MATLAB - Random Numbers

Generating random numbers is a fundamental task in simulation, statistics, cryptography, and testing. MATLAB provides a powerful and flexible suite of functions for creating random numbers from various distributions. The numbers generated are pseudorandom, meaning they are produced by a deterministic algorithm but are statistically indistinguishable from true random numbers.

This tutorial covers the core functions rand, randn, randi, and the modern best practice for controlling the random number generator for reproducible results.

Controlling the Random Number Generator: rng

Section titled “Controlling the Random Number Generator: rng”

Before generating numbers, it’s crucial to understand how to control the random number generator. This ensures your results are reproducible, which is essential for debugging, testing, and sharing research.

The modern, recommended function for this is rng.

  • rng('default'): Resets the generator to its default startup settings. Use this at the beginning of a script to ensure it always produces the same sequence of random numbers.
  • rng(seed): Seeds the generator with a specific integer seed. Using the same seed will always produce the same result. For example, rng(0).
  • rng('shuffle'): Seeds the generator based on the current time. This produces different results each time you run your code.
  • s = rng and rng(s): Saves the current state of the generator into a structure s, and later restores it. This is useful for reproducing a specific block of code without resetting the entire sequence.

Example: The Importance of Reproducibility

Section titled “Example: The Importance of Reproducibility”
% Without controlling the seed, results are different each time
disp('Run 1:');
disp(rand(1, 3));
disp('Run 2 (different results):');
disp(rand(1, 3));
% --- Now, with rng for reproducibility ---
rng('default'); % Set a known starting point
disp('Run 3 (reproducible):');
disp(rand(1, 3));
rng('default'); % Reset to the same starting point
disp('Run 4 (same as Run 3):');
disp(rand(1, 3));
% Expected Output:
% Run 1:
% 0.8147 0.9058 0.1270 (These values will vary on your system)
% Run 2 (different results):
% 0.9134 0.6324 0.0975 (These values will vary on your system)
% Run 3 (reproducible):
% 0.8147 0.9058 0.1270
% Run 4 (same as Run 3):
% 0.8147 0.9058 0.1270

The rand function generates random numbers from a continuous uniform distribution between 0 and 1.

SyntaxDescription
X = randReturns a single random scalar.
X = rand(n)Returns an n-by-n matrix of random numbers.
X = rand(sz1, sz2, ..., szN)Returns an sz1-by-sz2-by-…-by-szN array.
X = rand([sz1, sz2, ..., szN])Same as above, using a size vector.
X = rand(___, typename)Returns an array of type single or double.
rng(0); % For reproducible results
% A 3x3 matrix of random numbers
mat = rand(3, 3)
% A 2x4 matrix of single-precision random numbers
mat_single = rand(2, 4, 'single')
% Generate random numbers in a range [a, b]
% Formula: r = a + (b-a).*rand(sz)
a = 10;
b = 20;
random_in_range = a + (b-a).*rand(1, 5)
% Expected Output:
% mat =
% 0.8147 0.1576 0.6557
% 0.9058 0.9706 0.0357
% 0.1270 0.9572 0.8491
%
% mat_single =
% 2x4 single matrix
%
% 0.9340 0.3784 0.8600 0.8537
% 0.6787 0.8132 0.0154 0.0427
%
% random_in_range =
% 16.9457 17.7513 14.6096 16.5574 10.3571

The randn function generates random numbers from the standard normal distribution (mean = 0, standard deviation = 1). The syntax is identical to rand.

rng(1); % For reproducible results
% A 2x3 matrix from standard normal distribution
normal_mat = randn(2, 3)
% Generate numbers from a normal distribution with a specific mean and std. dev.
% Formula: r = mean + std_dev.*randn(sz)
mu = 50; % Mean
sigma = 5; % Standard Deviation
custom_normal = mu + sigma.*randn(1, 4)
% Expected Output:
% normal_mat =
% 0.4889 -1.0636 0.3394
% -1.0998 0.3149 1.3435
%
% custom_normal =
% 48.5137 52.2872 48.8358 46.1963

The randi function generates uniformly distributed pseudorandom integers.

SyntaxDescription
X = randi(imax)Returns a single integer between 1 and imax.
X = randi(imax, n)Returns an n-by-n matrix of integers.
X = randi([imin, imax], sz)Returns an array of size sz with integers in the range [imin, imax].
rng(100); % For reproducible results
% A single integer between 1 and 10 (like rolling a 10-sided die)
die_roll = randi(10)
% A 3x3 matrix of integers between -5 and 5
int_matrix = randi([-5, 5], 3, 3)
% Expected Output:
% die_roll =
% 9
%
% int_matrix =
% -4 1 -1
% 0 4 4
% -3 -3 5

The randperm function creates a random permutation of integers.

rng(2023); % For reproducible results
% A random permutation of integers from 1 to 8
% Useful for shuffling data
p1 = randperm(8)
% Select 4 unique random integers from the range 1 to 20
% Useful for random sampling without replacement
k_unique = randperm(20, 4)
% Expected Output:
% p1 =
% 2 3 8 1 4 5 7 6
%
% k_unique =
% 14 10 7 12