Main Content

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. Therefore, a command such as rand(2,2) returns the same result any time you execute it immediately following startup. Also, any script or function that calls the random number functions returns the same result whenever you restart.

If you want to avoid repeating the same random number arrays when MATLAB restarts, then execute the command,

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 at any time using

rng('default');
When you execute rng('default'), the ensuing random number commands return results that match the output of a new MATLAB session. For example,
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.

See Also