Main Content

Generate Random Numbers That Are Repeatable

Specify the Seed

This example shows how to repeat arrays of random numbers by specifying the seed first. Every time you initialize the generator using the same seed, you always get the same result.

First, initialize the random number generator to make the results in this example repeatable.

rng('default');

Now, initialize the generator using a seed of1.

rng(1);

Then, create an array of random numbers.

A = rand(3,3)
A = 0.4170 0.3023 0.1863 0.7203 0.1468 0.3456 0.0001 0.0923 0.3968

Repeat the same command.

A = rand(3,3)
A = 0.5388 0.2045 0.6705 0.4192 0.8781 0.4173 0.6852 0.0274 0.5587

The first call torandchanged the state of the generator, so the second result is different.

Now, reinitialize the generator using the same seed as before. Then reproduce the first matrix,A.

rng(1); A = rand(3,3)
A = 0.4170 0.3023 0.1863 0.7203 0.1468 0.3456 0.0001 0.0923 0.3968

In some situations, setting the seed alone will not guarantee the same results. This is because the generator that the random number functions draw from might be different than you expect when your code executes. For long-term repeatability, specify the seed and the generator type together.

For example, the following code sets the seed to1and the generator to Mersenne Twister.

rng(1,'twister');

Set the seed and generator type together when you want to:

  • 确保那t the behavior of code you write today returns the same results when you run that code in a future MATLAB®release.

  • 确保那t the behavior of code you wrote in a previous MATLAB release returns the same results using the current release.

  • Repeat random numbers in your code after running someone else’s random number code.

See therngreference page for a list of available generators.

Save and Restore the Generator Settings

This example shows how to create repeatable arrays of random numbers by saving and restoring the generator settings. The most common reason to save and restore generator settings is to reproduce the random numbers generated at a specific point in an algorithm or iteration. For example, you can use the generator settings as an aid in debugging. Unlike reseeding, which reinitializes the generator, this approach allows you to save and restore the generator settings at any point.

First, initialize the random number generator to make the results in this example repeatable.

rng(1,'twister');

Create an array of random integer values between 1 and 10.

A = randi(10,3,3)
A =3×35 4 2 8 2 4 1 1 4

The first call torandichanged the state of the generator. Save the generator settings after the first call torandiin a structures.

s = rng;

Create another array of random integer values between 1 and 10.

A = randi(10,3,3)
A =3×36 3 7 5 9 5 7 1 6

Now, return the generator to the previous state stored insand reproduce the second arrayA.

rng(s); A = randi(10,3,3)
A =3×36 3 7 5 9 5 7 1 6

See Also

Related Topics