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.
% Current settings of the random number generator gSettings = rng;
gSettings = Type: 'twister' Seed: 0 State: [625x1 uint32]
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 rng(7,'twister');
% Use 'Combined Multiple Recursive' with seed 10 rng(10,'combRecursive');
% Use 'Multiplicative Lagged Fibonacci' with seed based on the current time rng('shuffle','multFibonacci');
Random numbers in MATLAB are in fact pseudo-random numbers. If you call
rng to set the generator to a previous
type pair, the sequence of random numbers will repeat.
% Set up the generator and generate a matrix of random integers rng(15,'twister'); resultExample1 = randi(1000,[3,5]);
resultExample1 = 849 362 306 250 718 179 276 305 918 866 55 531 112 265 808
% Set up the generator and generate a matrix of random integers (again) rng(15,'twister'); resultExample2 = randi(1000,[3,5]);
resultExample2 = 849 362 306 250 718 179 276 305 918 866 55 531 112 265 808
Note: Your result in the preceding examples could be different due to the random nature of the operations.
I recommend the following books to learn more on random numbers in MATLAB.
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.
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.
- How to Create a Matrix of Random Floating-Point Numbers in MATLAB
- How to Create a Matrix of Random Integers in MATLAB
- How to Randomly Permute the Integers of a Range in MATLAB
- How to Create a Matrix of Non-Repeated Random Integers in MATLAB
- How to Create a Matrix of Random Floating-Point Numbers Within a Range in MATLAB
- How to Control the Generation of Random Numbers in MATLAB
- Why Does MATLAB Generate the Same Random Numbers in Each Session?
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.