How to Control the Generation of Random Numbers in MATLAB

The function rng controls the generation of random numbers.


rng configures the random number generator of MATLAB. This generator is the foundation of functions that use or generate random numbers, such as rand, randn, randi, and randperm.

The settings of the generator consist of a nonnegative integer that serves as seed, a type that indicates the algorithm used to generate random numbers, and a state.

The state changes each time MATLAB generates a new random number.
% Current settings of the random number generator
gSettings = rng;


rng(seed,type) sets the seed of the generator to the nonnegative integer seed, and the type to the string type. The syntax rng('shuffle',type) is almost equal, but the seed is set based on the current time.

rng('default') sets the generator to its default settings. By default, MATLAB uses the Mersenne Twister generator with seed 0.

% Use 'Mersenne Twister' with seed 7
% Use 'Combined Multiple Recursive' with seed 10
% Use 'Multiplicative Lagged Fibonacci' with seed based on the current time

Deeper look

Random numbers in MATLAB are in fact pseudo-random numbers. If you call rng to set the generator to a previous seed and type pair, the sequence of random numbers will repeat.

Note that resultExample1 and resultExample2 are equal.
% Set up the generator and generate a matrix of random integers
resultExample1 = randi(1000,[3,5]);
% Set up the generator and generate a matrix of random integers (again)
resultExample2 = randi(1000,[3,5]);

Note: Your result in the preceding examples could be different due to the random nature of the operations.

Further reading

I recommend the following books to learn more on random numbers in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. The first chapter covers random numbers, logical operators, and common elementary math functions, among other topics.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The third chapter covers random numbers, matrix sorting, and several data analysis functions, among other topics.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

doc rng;

Source code

I hope you have learned how to control the generation of random numbers in MATLAB. The source code developed in this tutorial is available at this page.


Your friends may need this knowledge to complete a task. Share this tutorial.