MATLAB generates the same sequence of random numbers in each session. Apply this procedure to verify this phenomenon:
- Close and open MATLAB to begin a new session
- Execute the code
A = rand(3)and write down the result
- Execute the code
B = randi(1000,3)and write down the result
- Repeat the steps 1–3
- Check that MATLAB generated the same values for
MATLAB generates the same sequence of random numbers in each session because at startup the random number generator is reset to the same state. By default, MATLAB uses the Mersenne Twister generator with seed 0.
% Set the generator to its default settings rng('default'); defaultSettings = rng;
defaultSettings = Type: 'twister' Seed: 0 State: [625x1 uint32]
Configure the random number generator with a unique seed at the beginning of each session, and MATLAB will generate a different set of random numbers.
% Seed the generator based on the current time rng('shuffle','twister');
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 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 why MATLAB generates the same random numbers in each session, and how to eradicate this behavior. The source code developed in this tutorial is available at this page.