Main Content

Control Random Number Generation

R2026b

This example shows how to control random number generation using the rng function.

You can generate random numbers in MATLAB® by using the rand, randi, randn, and randperm functions. These functions draw numbers from a shared global random number stream that you can control using rng. MATLAB provides several pseudorandom number generators for rng that produce deterministic sequences of numbers that appear random. Although these sequences are predictable when the generator algorithm, seed, and internal state are known, they pass statistical tests of randomness and satisfy the independent and identically distributed (i.i.d.) condition. For this reason, numbers generated by pseudorandom number generators are commonly referred to as random numbers.

Because the random number sequences are deterministic, you can control them to:

  • Repeat calculations that include random numbers and obtain the same results.

  • Generate different sequences of random numbers in different sessions.

Generate Repeating Sequences at Startup

By default, MATLAB returns the same sequence of random numbers each time you start a new session. This behavior occurs because MATLAB initializes the random number generator with a default algorithm and seed.

You can reset the generator to the startup settings by using rng("default"). In this example, rand(2) returns the same random numbers as at startup.

rng("default")
r = rand(2)
r = 2×2

    0.8147    0.1270
    0.9058    0.9134

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

To view the current generator settings, call rng with no inputs.

s = rng
s = struct with fields:
     Type: 'twister'
     Seed: 0
    State: [625×1 uint32]

Generate Nonrepeating Sequences in Different Sessions

Each call to rand, randi, randn, or randperm returns values generated from the shared global stream. Because MATLAB resets this stream at startup, separate sessions produce identical sequences unless you change the seed.

To generate different sequences in different sessions, reseed the random number generator using the current time.

rng("shuffle")
r = rand(2)
r = 2×2

    0.7000    0.4458
    0.7618    0.1621

Each call to rng("shuffle") initializes the generator with a seed based on the current time, so the sequence differs between sessions.

rng("shuffle")
s = rng
s = struct with fields:
     Type: 'twister'
     Seed: 130565393
    State: [625×1 uint32]

r = rand(2)
r = 2×2

    0.9916    0.5620
    0.6062    0.4371

Using rng("shuffle") prevents repeating the same sequence across sessions. However, it does not improve the statistical quality of the generated values or make them more random. In most workflows, you do not need to reseed repeatedly within a session. Once initialized, the generator produces random values with the expected statistical properties for that algorithm, where the values satisfy the i.i.d. condition. Using different seeds produces different sequences, but values drawn from separately seeded sequences do not necessarily satisfy the i.i.d. condition.

Because rng("shuffle") seeds the random number generator based on the current time, do not use this command when performing parallel computations on different workers, such as inside a parfor-loop. Instead, to generate different random numbers on different workers, use the default rng behavior or specify a unique substream on each worker using RandStream. For more information, see Create and Control Random Number Streams.

Specify Seed to Control Repeatability

In addition to calling rng("default") and rng("shuffle"), you can specify a seed directly. The seed sets the initial state of a random number generator and enables you to reproduce a sequence of random numbers.

Use the same seed and generator algorithm to repeat results. For example, specify a seed of 1 and the Mersenne Twister algorithm. Generate five random numbers in two successive calls using the same seed and algorithm. The generated random numbers are the same.

rng(1,"twister")
r = randn(1,5)
r = 1×5

   -0.6490    1.1812   -0.7585   -1.1096   -0.8456

rng(1,"twister")
r = randn(1,5)
r = 1×5

   -0.6490    1.1812   -0.7585   -1.1096   -0.8456

Use different seeds to generate different sequences. For example, generate five random numbers with a seed of 2 and then with a seed of 3.

rng(2,"twister")
r2 = randn(1,5)
r2 = 1×5

   -0.1242   -2.5415    0.2772   -0.1960   -0.1962

rng(3,"twister")
r3 = randn(1,5)
r3 = 1×5

    0.0685    0.9512   -0.3448    0.0359    1.1221

Changing the seed affects all subsequent calls to rand, randi, randn, and ranperm. For random number reproducibility, set the seed explicitly at a clear point in your code, typically at the beginning of a script or session.

Choose Generator Algorithm

In addition to specifying the seed, you can select the random number generator algorithm. Depending on your use case, select an algorithm that provides faster performance, supports parallel computation, produces values with higher precision, or meets more stringent statistical testing criteria. For more information, see Create and Control Random Number Streams.

For example, specify the SIMD-oriented fast Mersenne Twister algorithm with a seed of 0.

rng(0,"simdTwister")

For parallel computing support not available with the SIMD-oriented fast Mersenne Twister algorithm, specify the Threefry 4x64 generator algorithm.

rng(0,"threefry")

While rng("default") resets the generator to the default settings, these settings can vary across MATLAB releases or environments. For reproducible results, specify both the seed and the generator algorithm explicitly. This approach is useful when validating code or reproducing results across different MATLAB environments. For more information, see Specify Random Number Seed and Generator.

Save and Restore Random Number Generator Settings

Calling rng with no inputs returns a structure that contains the current generator algorithm, seed, and internal state.

s = rng
s = struct with fields:
     Type: 'threefry'
     Seed: 0
    State: [17×1 uint32]

The State field represents the internal state of the random number generator. The generator maintains this state vector internally to produce the next value in the sequence of random numbers. Each call to rand, randi, randn, or randperm transforms this state to produce successive values that satisfy the i.i.d. condition.

Because the state determines the current position in the sequence, the structure returned by rng contains all the information needed to resume random number generation from a specific point. Do not modify or construct your own state vector. Instead, use rng to save the structure and restore it later to reproduce results.

For example, generate some random numbers and save the generator settings. Then generate an array of five more random numbers.

r1 = randn(10,10);
s = rng;
r2 = randn(1,5)
r2 = 1×5

   -0.6350    0.3072   -0.3319   -1.0498    0.2324

Generate more random numbers and restore the generator settings to the previous settings. Then generate another array of five more random numbers.

r3 = randn(5,5);
rng(s);
r4 = randn(1,5)
r4 = 1×5

   -0.6350    0.3072   -0.3319   -1.0498    0.2324

The two arrays of five random numbers are the same.

tf = isequal(r2,r4)
tf = logical
   1

If you specify the same seed, you can reproduce a sequence from the beginning. In contrast, saving and restoring the internal state of a random number generator lets you resume generating numbers from any point in the sequence.

Choose Between rng and RandStream

Use rng to control the shared global random number stream for generating random numbers. For more advanced control of random number streams, such as creating multiple independent streams or choosing normal transformation algorithms, use the RandStream object.

See Also

| | | | |

Topics