%% Managing the Global Stream Using RandStream
% The rand, randn, randi, and randperm functions draw random numbers from an underlying random number stream, called the global stream. The global stream is a RandStream object. A simple way to control the global stream is to use the rng function. For more comprehensive control, the RandStream class enables you to create a separate stream from the global stream, get a handle to the global stream, and control random number generation.
% Use rng to set the random number generator to the default seed (0) and algorithm (Mersenne Twister). Save the generator settings.

rng('default')
s = rng

% Create a 1-by-6 row vector of random values between 0 and 1.

x = rand(1,6)

% Use RandStream.getGlobalStream to return a handle to the global stream, that is, the current global stream that rand generates random numbers from. If you use RandStream.getGlobalStream to get a handle to the global stream, you can see the changes you made to the global stream using rng.

globalStream = RandStream.getGlobalStream

% Change the generator seed and algorithm, and create a new random row vector. Show the current global stream that rand generates random numbers from.

rng(1,'philox')
xnew = rand(1,6)
globalStream = RandStream.getGlobalStream

% Next, restore the original generator settings and create a random vector. The result matches the original row vector x created with the default generator.

rng(s)
xold = rand(1,6)

% By default, random number generation functions, such as rand, use the global random number stream. To specify a different stream, create another RandStream object. Pass it as the first input argument to rand. For example, create a 1-by-6 vector of random numbers using the SIMD-oriented Fast Mersenne Twister.

myStream = RandStream('dsfmt19937')
r = rand(myStream,1,6)

% When you call the rand function with myStream as the first input argument, it draws numbers from myStream and does not affect the results of the global stream.
% If you want to set myStream as a global stream, you can use the RandStream.setGlobalStream object function.

RandStream.setGlobalStream(myStream)
globalStream = RandStream.getGlobalStream

% In many cases, the rng function is all you need to control the global stream, but the RandStream class allows control over some advanced features, such as the choice of algorithm used for normal random values.
% For example, create a RandStream object and specify the transformation algorithm to generate normally distributed pseudorandom values when using randn. Generate normally distributed pseudorandom values using the Polar transformation algorithm, instead of the default Ziggurat transformation algorithm.

myStream = RandStream('mt19937ar','NormalTransform','Polar')

% Set myStream as the global stream. Create 6 random numbers with uniform distribution from the global stream.

RandStream.setGlobalStream(myStream)
randn(1,6)

%
% Copyright 2020 The MathWorks, Inc.