Why Do Random Numbers Repeat After Startup?

All the random number functions, `rand`, `randn`, `randi`, and `randperm`, draw values from a shared random number generator. Every time you start MATLAB®, the generator resets itself to the same state using the default algorithm and seed. Therefore, a command such as `rand(2,2)` returns the same result any time you execute it immediately following startup in different MATLAB sessions that have the same preferences for the random number generator. Also, any script or function that calls the random number functions returns the same result whenever you restart.

When you first start a MATLAB session or call `rng("default")`, MATLAB initializes the random number generator using the default algorithm and seed. Starting in R2023b, you can set the default algorithm and seed in MATLAB preferences. If you do not change these preferences, then `rng` uses the factory value of `"twister"` for the Mersenne Twister generator with seed 0, as in previous releases. For more information, see Default Settings for Random Number Generator and Reproducibility for Random Number Generator.

• If you want to avoid repeating the same random number arrays when MATLAB restarts, then use `rng("shuffle")` before calling `rand`, `randn`, `randi`, or `randperm`. This command ensures that you do not repeat a result from a previous MATLAB session.

• If you want to repeat a result that you got at the start of a MATLAB session without restarting, you can reset the generator to the startup state using `rng("default")`.

When you execute `rng("default")`, the ensuing random number commands return results that match the output of another MATLAB session that uses the same default algorithm and seed for the random number generator.

```rng("default"); A = rand(2,2)```
```A = 0.8147 0.1270 0.9058 0.9134 ```
The values in `A` match the output of `rand(2,2)` whenever you restart MATLAB using the same preferences for the random number generator.

Alternatively, you can repeat a result by specifying the seed and algorithm used for the random number generator. For example, sets the seed to `1` and the generator algorithm to Mersenne Twister

`rng(1,"twister");`

Create an array of random numbers.

`A = rand(2,2)`
```A = 0.4170 0.0001 0.7203 0.3023```

Next, in a new MATLAB session, repeat the same commands to reproduce the array `A`.

```rng(1,"twister"); A = rand(2,2)```
```A = 0.4170 0.0001 0.7203 0.3023```