Skip to Main Content Skip to Search
Product Documentation

rng - Control random number generation

Syntax

rng(sd)
rng('shuffle')
rng(sd, generator)
rng('shuffle', generator)
rng('default')
s = rng
rng(s)
s = rng(...)

Description

rng(sd) seeds the random number generator using the nonnegative integer sd so that rand, randi, and randn produce a predictable sequence of numbers.

rng('shuffle') seeds the random number generator based on the current time so that rand, randi, and randn produce a different sequence of numbers after each time you call rng.

rng(sd, generator) and rng('shuffle', generator) additionally specify the type of the random number generator used by rand, randi, and randn. The generator input is one of:

GeneratorDescription
'twister'Mersenne Twister
'combRecursive'Combined Multiple Recursive
'multFibonacci'Multiplicative Lagged Fibonacci
'v5uniform'Legacy MATLAB 5.0 uniform generator
'v5normal'Legacy MATLAB 5.0 normal generator
'v4'Legacy MATLAB 4.0 generator

rng('default') puts the settings of the random number generator used by rand, randi, and randn to their default values so that they produce the same random numbers as if you restarted MATLAB. In this release, the default settings are the Mersenne Twister with seed 0.

s = rng returns the current settings of the random number generator used by rand, randi, and randn. The settings are returned in a structure s with fields 'Type', 'Seed', and 'State'.

rng(s) restores the settings of the random number generator used by rand, randi, and randn back to the values captured previously by s = rng.

s = rng(...) additionally returns the previous settings of the random number generator used by rand, randi, and randn before changing the seed, generator type, or the settings.

Examples

Example 1 — Retrieve and Restore Generator Settings

Save the current generator settings in s:

s = rng;

Call rand to generate a vector of random values:

x = rand(1,5)
x =
    0.8147    0.9058    0.1270    0.9134    0.6324

Restore the original generator settings by calling rng. Generate a new set of random values and verify that x and y are equal:

rng(s);
y = rand(1,5)
y =
    0.8147    0.9058    0.1270    0.9134    0.6324

Example 2 — Restore Settings for Legacy Generator

Use the legacy generator.

oldS = rng(0,'v5uniform')
x = rand

oldS = 
     Type: 'twister'
     Seed: 0
    State: [625x1 uint32]

x =
    0.9501

Restore the previous settings by calling rng:

rng(oldS)

See Also

now | rand | randi | randn | RandStream

  


» Learn more
» Download free kit
» Get trial software

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS