Main Content

RandStream

R2026b

Random number stream

Description

RandStream creates a random number stream by using a specified random number generator algorithm or by copying an existing stream.

You can generate random numbers in MATLAB® from one or more random number streams. The simplest way to generate arrays of random numbers is to use the rand, randi, randn, and randperm functions. These functions all rely on the same stream of uniformly distributed random numbers, known as the global stream. To change the global stream, create a stream using RandStream and then call RandStream.setGlobalStream. However, for most use cases, you can use the rng function, which provides a simpler interface for controlling the global stream.

You can also use RandStream to create individual streams and generate random numbers from them by using rand, randi, randn, or randperm. Numbers generated from these streams are separate from those generated from the global stream or from other streams. For details, see Object Functions.

Creation

Use the following syntaxes to create a single random number stream. To create multiple independent streams simultaneously, use the RandStream.create function.

Description

s = RandStream(generator) creates a random number stream that uses the uniform random number generator algorithm specified by generator.

example

s = RandStream(generator,Name=Value) specifies additional options using one or more name-value arguments.

example

s = RandStream(existingStream) creates a copy of an existing random number stream with the same properties and state. When you generate random numbers using the newly copied stream and the existing stream, sampling from one stream does not affect the other. You can also copy an existing random number stream by using the copy method. (since R2026b)

Input Arguments

expand all

Random number generator algorithm, specified as a string scalar or character vector containing an algorithm or name from the following table. For example, to create a random number stream using the SIMD-oriented fast Mersenne Twister, you can call s = RandStream("dsfmt19937") or s = RandStream("simdTwister"). This table describes the available algorithms. Some algorithms support multiple streams and substreams to create sets of random numbers that are mutually independent. For more information, see Create and Control Random Number Streams.

AlgorithmNameMultiple Stream and Substream SupportDescriptionApproximate Period in Full Precision

"dsfmt19937"

"simdTwister"NoSIMD-oriented fast Mersenne Twister 219937 – 1

"mcg16807"

"v4"NoMultiplicative congruential generator231 – 2

"mlfg6331_64"

"multFibonacci"YesMultiplicative lagged Fibonacci generator2124 (251 streams of length 272)

"mrg32k3a"

"combRecursive"YesCombined multiple recursive generator2191 (263 streams of length 2127)

"mt19937ar"

"twister"NoMersenne Twister219937 – 1

"pcg64dxsm" (since R2026b)

"pcg"Yes64-bit permuted congruential generator with double xor-shift multiply2255 (263 streams of length 2192)

"philox4x32_10"

"philox"YesPhilox 4x32 generator with 10 rounds2193 (264 streams of length 2129)

"shr3cong"

"v5normal"NoSHR3 shift-register generator summed with linear congruential generator264

"swb2712"

"v5uniform"NoModified subtract-with-borrow generator21492

"threefry4x64_20"

"threefry"YesThreefry 4x64 generator with 20 rounds2514 (2256 streams of length 2258)

"xoshiro256pp" (since R2026b)

"xoshiro"YesXor-shift-rotate generator with 256-bit state and double addition2256 (264 streams of length 2192)

This argument sets the Type property.

Random number stream, specified as a RandStream object.

Name-Value Arguments

expand all

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Example: s = RandStream("mt19937ar",Seed=15,NormalTransform="Polar")

Random number generator seed, specified as a nonnegative integer less than 2^32 or "shuffle". The seed specifies the starting point of the algorithm used to generate random numbers. "shuffle" creates a seed based on the current time. If you specify an integer, it must be between 0 and 232 − 1.

Specify the generator seed as an initialization step when creating a stream at MATLAB startup or before running a simulation. To reproduce a stream, use the same seed. Although using multiple seeds creates multiple sequences of random numbers, these sequences are not guaranteed to be statistically independent. To create streams that are statistically independent, specify the Substream property or use RandStream.create with multiple outputs.

This argument sets the Seed property.

Normal transformation algorithm to generate normally distributed random numbers using randn, specified as "Ziggurat", "Polar", or "Inversion". For more information, see Create and Control Random Number Streams.

The default normal transformation algorithm depends on the specified generator algorithm:

  • "Ziggurat" is the default for dsfmt19937, mlfg6331_64, mrg32k3a, mt19937ar, shr3cong, and swb2712.

  • "Polar" is the default for mcg16807.

  • "Inversion" is the default for pcg64dxsm, philox4x32_10, threefry4x64_20, and xoshiro256pp.

This argument sets the NormalTransform property.

Since R2026b

Option to generate antithetic random numbers, specified as a numeric or logical 0 (false) or 1 (true). When you set Antithetic to true, each uniformly distributed random number u from the original random number stream is transformed to 1-u, producing antithetic variates. This transformation creates negatively correlated sample pairs, which are useful for variance reduction in Monte Carlo simulations.

This argument sets the Antithetic property.

Since R2026b

Option to use full precision when generating random numbers, specified as a numeric or logical 1 (true) or 0 (false). When you set FullPrecision to false, some generators can produce random numbers faster by using fewer bits.

This argument sets the FullPrecision property.

Output Arguments

expand all

Random number stream, returned as a RandStream object.

Properties

expand all

A random number stream s has properties that control its behavior. Access a property using p = s.Property and modify one using s.Property = p. To save and restore all properties of a stream s, you can use A = get(s) and set(s,A), respectively. This list describes the properties of RandStream.

This property is read-only.

Random number generator algorithm, returned as a character vector containing the algorithm used by the stream. See the table of generator algorithms for names and descriptions of the algorithms.

Not all generator algorithms support multiple streams. For some generators, you can create multiple streams and substreams that are statistically independent.

Data Types: char

This property is read-only.

Random number generator seed used to create the stream, returned as a nonnegative integer.

Data Types: uint32

This property is read-only.

Number of streams in the group in which the current stream was created, returned as a positive integer.

Data Types: uint64

This property is read-only.

Index of the current stream from among the group of streams with which it was created, returned as a positive integer.

Data Types: uint64

Current internal state of the stream, specified as a vector of integers. The size and data type of the state vector depends on the generator algorithm. When you set this property, the value you assign to s.State must be a value read from s.State previously. Use reset to return a stream to its initial state without having previously read from the State property. Saving and restoring the internal state of the stream with the State property allows you to reproduce a sequence of random numbers.

The internal state determines the sequence of random numbers produced by the random number stream s. Every time you generate random numbers from a single stream, the state of the stream is transformed to create successive values that are statistically independent and identically distributed.

Note

Only restore the state of a random number stream, or reset a stream, to reproduce results from the stream.

Data Types: uint32 | uint64 | double

Index of the substream to which the stream is currently set, specified as a positive integer.

For some generator algorithms, you can create different substreams from a random stream. Values generated from different substreams are mutually independent. See the table of generator algorithms for generators that support substreams.

Data Types: double

Normal transformation algorithm to generate normally distributed random numbers using randn, specified as 'Ziggurat', 'Polar', or 'Inversion'.

The default normal transformation algorithm depends on the specified generator algorithm:

  • 'Ziggurat' is the default for dsfmt19937, mlfg6331_64, mrg32k3a, mt19937ar, shr3cong, and swb2712.

  • 'Polar' is the default for mcg16807.

  • 'Inversion' is the default for pcg64dxsm, philox4x32_10, threefry4x64_20, and xoshiro256pp.

Data Types: char

Option to generate antithetic random numbers, specified as a numeric or logical 0 (false) or 1 (true). When you set Antithetic to true, each uniformly distributed random number u from the original random number stream is transformed to 1-u, producing antithetic variates. This transformation creates negatively correlated sample pairs, which are useful for variance reduction in Monte Carlo simulations.

Data Types: logical

Option to use full precision when generating random numbers, specified as a numeric or logical 1 (true) or 0 (false). When you set FullPrecision to false, some generators can produce random numbers faster by using fewer bits. However, two streams that have identical properties except for FullPrecision can produce different sequences of random numbers.

Data Types: logical

Object Functions

Other object functions of RandStream are:

RandStream.createCreate statistically independent random number streams
RandStream.listList available random number generator algorithms
RandStream.getGlobalStreamGet current global random number stream
RandStream.setGlobalStreamSet global random number stream
resetReset random number stream

By default, random number generation functions, such as rand, use the global random number stream. To specify a different stream, create a RandStream object and pass it as the first input argument. For instance, create a 4-by-1 vector of random numbers using the SIMD-oriented fast Mersenne Twister.

s = RandStream("dsfmt19937");
r = rand(s,4,1);

The functions in this table accept a RandStream object.

randUniformly distributed random numbers

Supported syntaxes, where s is a RandStream object:

X = rand(s)
X = rand(s,n)
X = rand(s,sz1,...,szN)
X = rand(s,sz)
X = rand(s,__,typename)
X = rand(s,__,like=p)
For details on other input arguments, see rand, randi, and randn.

randiUniformly distributed random integers
randnNormally distributed random numbers
randpermRandom permutation of integers

Supported syntaxes, where s is a RandStream object:

p = randperm(s,n)
p = randperm(s,n,k)
For details on other input arguments, see randperm.

Examples

collapse all

Create a random number stream using the SIMD-oriented fast Mersenne Twister algorithm.

s = RandStream("dsfmt19937")
s = 
dsfmt19937 random stream
             Seed: 0
  NormalTransform: Ziggurat

Use the stream to generate five random numbers.

r = rand(s,1,5)
r = 1×5

    0.0306    0.2131    0.2990    0.3811    0.8635

Create a random number stream using a generator seed based on the current time. Avoid doing so more than once per MATLAB session because reseeding can affect the statistical properties of the generated random numbers.

s = RandStream("mt19937ar",Seed="shuffle");

Use the stream to create a 3-by-3 matrix of random numbers with uniform distribution between 0 and 1.

M = rand(s,3)
M = 3×3

    0.0421    0.3526    0.7033
    0.6228    0.6069    0.5075
    0.7050    0.6126    0.5716

Generate another five random numbers from the stream.

r = rand(s,1,5)
r = 1×5

    0.1959    0.5059    0.4874    0.0872    0.5584

Create a 2-by-3 matrix of single-precision numbers.

M = single([0.1 -3 2.5; 1.2 -3.4 6]);

Create a random number stream whose seed is zero.

s = RandStream("mcg16807",Seed=0);

Use the stream to generate an array of random numbers that is the same size and data type as M.

R = rand(s,size(M),like=M)
R = 2×3 single matrix

    0.2190    0.6789    0.9347
    0.0470    0.6793    0.3835

Create a random number stream whose seed is zero.

s = RandStream("mcg16807",Seed=0);

Generate five random numbers from the stream. Every time you generate a number from the stream, the generator algorithm transforms the internal state such that the next generated number is independent and identically distributed from the previous number.

r1 = rand(s,1,5)
r1 = 1×5

    0.2190    0.0470    0.6789    0.6793    0.9347

Save the current state of the generator. Generate another five random numbers.

savedState = s.State;
r2 = rand(s,1,5)
r2 = 1×5

    0.3835    0.5194    0.8310    0.0346    0.0535

To reproduce the last outcome of five random numbers, restore the generator state to the saved state.

s.State = savedState;
r3 = rand(s,1,5)
r3 = 1×5

    0.3835    0.5194    0.8310    0.0346    0.0535

Read and write the generator state only when you want to reproduce a specific outcome from the stream.

Create a random number stream whose seed is 3. Use the stream to generate eight random numbers.

stream = RandStream("dsfmt19937",Seed=3);
r = rand(stream,1,8)
r = 1×8

    0.2550    0.8753    0.0908    0.1143    0.3617    0.8210    0.8444    0.6189

Reset the random number stream to its initial state with a seed of 3. Reproduce the eight random numbers that were generated.

reset(stream,3);
r = rand(stream,1,8)
r = 1×8

    0.2550    0.8753    0.0908    0.1143    0.3617    0.8210    0.8444    0.6189

Resetting the seed of a stream can invalidate independence with other streams. Reset a stream only when you want to reproduce results from the stream.

Create two random number streams. Set the first stream as the global stream by using RandStream.setGlobalStream.

globalStream = RandStream("mlfg6331_64",NormalTransform="Polar")
globalStream = 
mlfg6331_64 random stream
             Seed: 0
  NormalTransform: Polar

RandStream.setGlobalStream(globalStream)

To show the current global stream, use RandStream.getGlobalStream.

RandStream.getGlobalStream
ans = 
mlfg6331_64 random stream (current global stream)
             Seed: 0
  NormalTransform: Polar

Create a second stream myStream that acts separately from the new global stream.

myStream = RandStream("dsfmt19937",NormalTransform="Inversion")
myStream = 
dsfmt19937 random stream
             Seed: 0
  NormalTransform: Inversion

Generate three random numbers from the global stream. Generate another three random numbers from the local stream myStream that you created.

r1 = randn(1,3)
r1 = 1×3

    0.8715    1.0588   -0.6956

r2 = randn(myStream,1,3)
r2 = 1×3

   -1.8723   -0.7956   -0.5273

When you call the functions rand, randn, randi, and randperm without specifying a stream, they draw from the global stream and do not affect results that you generate with any local streams.

For some generator algorithms, you can create different substreams from a random stream. Numbers generated from different substreams are mutually independent.

For example, create a random number stream using a combined multiple recursive generator.

s = RandStream("mrg32k3a");

To reposition a stream to a particular substream, set its Substream property. For instance, generate random numbers in a loop. Position the random number stream to the beginning of a different substream at the beginning of each iteration of the loop. Generate three mutually independent sets of five random numbers.

for i = 1:3
  s.Substream = i;
  r = rand(s,1,5)
end
r = 1×5

    0.7270    0.4522    0.9387    0.2360    0.0277

r = 1×5

    0.5582    0.8527    0.7733    0.0633    0.2788

r = 1×5

    0.1666    0.2924    0.7728    0.8391    0.5107

To reproduce the second set of five random numbers, reposition the stream to the corresponding substream.

s.Substream = 2;
r = rand(s,1,5)
r = 1×5

    0.5582    0.8527    0.7733    0.0633    0.2788

More About

expand all

Tips

  • RandStream creates a random number stream that you can use to generate random, in-memory MATLAB arrays. To create a random number stream that you can use to generate GPU arrays, use parallel.gpu.RandStream (Parallel Computing Toolbox).

Extended Capabilities

expand all

Version History

Introduced in R2008b

expand all