MATLAB resets the random number generator to the same state at the beginning of each session.

## Test

MATLAB generates the same sequence of random numbers in each session. Apply this procedure to verify this phenomenon:

1. Close and open MATLAB to begin a new session
2. Execute the code `A = rand(3)` and write down the result
3. Execute the code `B = randi(1000,3)` and write down the result
4. Repeat the steps 1–3
5. Check that MATLAB generated the same values for `A` and `B`

## Explanation

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;``````

## Solution

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.

1. 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 other tutorials in this series.

## Source code

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.