rng
Controls the seed and generator of the global random number stream.
Category: Mathematics > Random Number Generation
Syntax
rng(seed)
Seeds the Mersenne Twister generator with a nonnegative integer.
rng('default')
Restores the startup settings: Mersenne Twister, seed 0.
rng('shuffle')
Seeds from the current time, giving a different sequence each run.
rng(seed, generator)
Chooses the generator, for example 'twister'.
s = rng
Returns the current settings as a struct, to restore later with rng(s).
Description
rng sets the state of the global stream, which is what rand, randn, randi and randperm use. Seeding with the same value before a computation makes it reproducible: it is the first line of most scripts that use random data.
To run a piece of code and then go back to the previous random state, save s = rng first and call rng(s) afterward.
Input arguments
seed- Nonnegative integer,
'default'or'shuffle'. generator- Generator name:
'twister'(or'mt19937ar'). s- Struct with fields
Type,SeedandState, as returned byrng.
Output arguments
s- The settings in effect before the call.
Example
Reproducible numbers and saved state
rng(42);
a = rand;
rng(42);
b = rand;
a == b
s = rng;
x = rand(1, 2);
rng(s);
isequal(x, rand(1, 2))
rng('default');
rand
ans = logical
1
ans = logical
1
ans = 0.8147
Notes
Only the Mersenne Twister generator ('twister') is available. The rand values for a given seed match MATLAB's; randn, randi and randperm may not.