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,


before calling rand, randn, randi, or randperm to ensure that you do not repeat a result from a previous MATLAB session.

There also can be situations in which you want to repeat a result that you got at the start of a MATLAB session, but you do not want to restart to do it. You can reset the generator to the startup state at any time in a MATLAB session:


When you execute rng('default'), the ensuing random number commands return results that match the output of a new MATLAB session. For example,

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

Was this topic helpful?