# New Ways With Random Numbers, Part I26

Posted by Loren Shure,

Today I'd like to introduce a guest blogger, Peter Perkins, who is a statistical software developer here at The MathWorks. In his life prior to The MathWorks, he worked as a statistician doing marine mammal research for the U.S. National Marine Fisheries Service, and one of his interests in MATLAB is random number generation and Monte-Carlo simulation.

### Contents

Almost everyone who's used MATLAB has used the rand or randn functions at one time or another. The way people use them varies widely, though. Sometimes, you might just want to fill in a vector or matrix with values other than 0 or 1, in order to try out some new lines of code that you've written. At the other end of the spectrum, you might be running a Monte-Carlo simulation where the statistical properties of the pseudo-random values matter.

But regardless of the context, one of the questions I consistently hear is, "How and when should I initialize or reinitialize or reset MATLAB's random number generator?" The answer I usually give is, annoyingly, another question: "Why do you want to do that?" That's because messing with the state of a random number generator can affect the statistical properties of the values it generates, and the right answer to the original question depends on the context - quite often, the answer is "Don't." There's a lot that could be said about the when and the why, and I'll touch on that. But mostly, I want to show some of the how that's new in MATLAB R2008b.

If you want to run the code that I used to create this blog entry, you'll need R2008b or later, and you'll want to start with a fresh MATLAB session, or else execute these two commands (don't worry, I'll explain what they do).

    mtstream = RandStream('mt19937ar');
RandStream.setDefaultStream(mtstream);

### Random Streams in MATLAB

Quite often, you don't need to worry about streams at all; MATLAB creates one for you when it starts up. rand, randn, and the new randi function draw values from that stream, and you can generate random numbers without ever knowing or caring what stream they come from. And there's nothing wrong with that - if the random number generators in MATLAB are doing their job correctly (and in R2008b, you have a choice among three generators based on state-of-the-art algorithms), you should be able to just generate random numbers using rand, randn or randi, and treat everything they return as independent random values.

But how do you go back and reproduce the random values you generate or otherwise control how they're generated? There's a new way to do that: you interact with a new kind of object in MATLAB, one that represents a random stream. Let's get the stream that MATLAB creates at startup.

defaultStream = RandStream.getDefaultStream()
defaultStream =
mt19937ar random stream (current default)
Seed: 0
RandnAlg: Ziggurat


The "mt19937ar" indicates that this stream generates values using the most common of the Mersenne Twister algorithms, the same algorithm that's been underneath rand for several releases. There are other generator choices; more about that in a moment. MATLAB created the stream using a seed of 0; more about that in a moment as well.

What's RandnAlg? One of the things that's new in R2008b is that randn draws values from the same stream as rand, although of course the uniform values have to be transformed to a standard normal distribution. The stream shown here makes that transformation using the Ziggurat algorithm, although you can change it (sorry, no more about that; you'll have to read the doc).

Finally, the display for this stream shows that it is the default stream. That just means that it's the stream that rand, randn, and randi draw their values from. Below, I'll show how you can create your own stream, and make it the default. There are a couple of reasons why you might want to do that. But first, let's see how to use the default stream to reproduce results.

### Resetting a Random Stream

Sometimes it's useful to be able to reproduce the output from MATLAB's random number generators. For example, you might want to rerun a Monte-Carlo simulation repeatedly, using exactly the same random values because you are debugging the code. In fact, MATLAB initializes the default random stream to the same internal state each time it starts up, so the same calls to rand, randn, and randi will return the same "random" values every you start MATLAB (unless you take steps - more about that in a minute). But it would be tedious to have to restart MATLAB each time you wanted to rerun a simulation.

The simplest way to reproduce random number generator output is to reset the default stream, which puts that stream back to the state it had when initially created.

reset(defaultStream)
z1 = randn(1,5)
z1 =
0.53767       1.8339      -2.2588      0.86217      0.31877


If I do it again, I'll get the same values again.

reset(defaultStream)
z2 = randn(1,5)
z2 =
0.53767       1.8339      -2.2588      0.86217      0.31877


While simple, reset is kind of a blunt instrument, and provides reproducibility only on a very gross scale - it's as if you restarted MATLAB. It's not something you should do unless you really want to reuse the same random sequence over again.

### Seeding a Stream

All pseudo-random number generators have the notion of a seed. Think of a stream as a very long sequence of values, wrapped into a circle, because it repeats when exhausted. Think of a seed as a starting position on the circle that you specify when you create a stream. There are (usually) many more random values than there are seeds, so it's not possible to start just anywhere by specifying a seed. And there's usually no simple description of where, say, the seed 0 lies in relation to, say, the seeds 1 or 2 other than knowing that they represent different starting positions. But if you create a stream with the same seed, you'll get the same sequence of values every time.

When MATLAB starts, it creates the default stream with commands equivalent to

stream0 = RandStream('mt19937ar','Seed',0)
RandStream.setDefaultStream(stream0);
stream0 =
mt19937ar random stream
Seed: 0
RandnAlg: Ziggurat


We saw that earlier. If I create a new stream with a different seed, such as

stream1 = RandStream('mt19937ar','Seed',1)
stream1 =
mt19937ar random stream
Seed: 1
RandnAlg: Ziggurat


and make it the default stream,

RandStream.setDefaultStream(stream1);

I'll get a different sequence of random values.

randn(1,5)
ans =
-0.64901       1.1812     -0.75845      -1.1096     -0.84555


But if I always use the same seed, I'll always get the same random number stream. This is a lot like resetting the current default stream - in fact, reset is nothing more than reseeding. The main difference between how I used reset above and here is that here, I've created my own stream, so I know exactly what I'm getting. Before, I'd get repeatability, but the specific random values depended on what generator algorithm was underneath the current default stream.

Reseeding is kind of a big hammer - you would not want to create new streams every time you needed a set of random values. It's most useful if you use it as an initialization step, perhaps at MATLAB startup, perhaps before running a simulation.

### Using Substreams for Reproducibility

We've seen that a drawback of using reset or 'Seed' to reproduce results is that you essentially have to start over from the beginning. A new feature in R2008b, substreams, provides a new way around that drawback.

Remember the circle? Substreams are nothing more than fixed "checkpoints" in a random number stream, defined by their position around the circle, spaced evenly at very large intervals. The substreams themselves are indexed beginning at 1, and you can jump to the beginning of a substream by setting a stream's Substream property. Values generated from different substreams are statistically independent in the same sense as consecutive values in a stream are.

Two new generator algorithms in R2008b support substreams: the Combined Multiple Recursive ('mrg32k3a') and the Multiplicative Lagged Fibonacci ('mlfg6331_64') generators (the doc has references). I'll create one of the former, and make it the default stream.

stream = RandStream('mrg32k3a');
RandStream.setDefaultStream(stream);

To reposition a stream to the beginning of a particular substream, I just set its Substream property.

stream.Substream = 2;

Much like seeds, substreams are nothing more than aliases for particular points along a sequence of random values. So what's different about them? There are some differences that I'll get into next time, but for now, the most obvious difference is that you can jump between substreams without having to create a new stream. It's a fairly lightweight operation.

Let's see what happens if I position a random number stream to the beginning of a substream before each iteration of a loop.

for i = 1:5
stream.Substream = i;
z = rand(1,i)
end
z =
0.72701
z =
0.5582      0.85273
z =
0.16662      0.29236      0.77278
z =
0.34773      0.38864      0.80161      0.95025
z =
0.56709      0.68377      0.29879      0.59318      0.69247


Now I can reproduce results from the 3rd iteration simply by repositioning the stream to the corresponding substream. I didn't have to rerun the whole loop, and I didn't even have to know beforehand that I wanted to look at this iteration.

i = 3;
stream.Substream = i;
z = rand(1,i)
z =
0.16662      0.29236      0.77278


If that loop were a time-consuming Monte-Carlo simulation, it would be a real boon to be able to go recreate and investigate any specific iteration without rerunning the whole thing.

Keep in mind that you don't need to overuse substreams. They're there to use, you don't have to worry about "using up" all the values in each substream before moving to the next one, but it would be pointless to take the other extreme and jump to a different substream every time you generate a new value. Substreams don't add randomness, they just make it easier to reproduce values.

### Saving and Restoring State

rand and randn are pseudorandom number generators, and all pseudorandom generator algorithms have an internal state that determines what the next value will be. It's a deterministic algorithm. Remember the circle? Each point along the circle corresponds to a different state. But for almost all modern algorithms, the state is more complicated than just the last number generated or a simple index of the current position in the stream.

Let's get the state of the default generator. To do that, I'll read the State property.

defaultStream = RandStream.getDefaultStream()
savedState = defaultStream.State;
whos savedState
defaultStream =
mrg32k3a random stream (current default)
Seed: 0
RandnAlg: Ziggurat
Name             Size            Bytes  Class     Attributes

savedState      12x1                48  uint32



If I call rand to generate a few random values,

u1 = rand(1,5)
u1 =
0.83911      0.51069      0.84469      0.68938      0.23777


and then I restore the state that I saved,

defaultStream.State = savedState;

rand will generate those exact same values the next time I call it.

u2 = rand(1,5)
u2 =
0.83911      0.51069      0.84469      0.68938      0.23777


The same is also true for randn and for randi. And because all three functions draw values from the same default stream, there's only one state to worry about - the default stream's state. I can use the state I saved earlier to reproduce results from randn, for example.

defaultStream.State = savedState;
z1 = randn(1,5)
z1 =
0.048564      0.87031      0.52365     0.095609     -0.79233

defaultStream.State = savedState;
z2 = randn(1,5)
z2 =
0.048564      0.87031      0.52365     0.095609     -0.79233


It's important to remember that because there's a single default stream, calling one function affects what specific values the others return.

savedState = defaultStream.State;
u1 = rand(1,5)
u2 = rand(1,5)
u1 =
0.045212      0.48758      0.75138      0.36639       0.5676
u2 =
0.10969      0.27046      0.10359      0.87516      0.28295

defaultStream.State = savedState;
% This returns the same vector as before
u1 = rand(1,5)
% Call randn in between the two calls to rand
z = randn(1,5);
% This returns different values than before
u2 = rand(1,5)
u1 =
0.045212      0.48758      0.75138      0.36639       0.5676
u2 =
0.20425     0.043083      0.54273      0.10648      0.20139


The functions do not act independently with respect to the values they return, however, the values generated by the three functions can still be treated as statistically independent regardless of what order you generate them in.

One practical application of saving and restoring the state might be to reproduce an entire Monte-Carlo simulation run, by saving the state before running it. Another might be to recreate one particularly interesting iteration in a Monte-Carlo simulation, having saved the state before that iteration. Another might be to recreate just one call to rand that happened deep in your code, so that you can recreate that call elsewhere, perhaps for debugging. As long as you have saved the state at the appropriate point, you can "jump to" anywhere in the sequence of random values. That's the advantage over resetting or seeding a stream, but it's the catch too: you have to have saved the right state beforehand.

As an aside, the internal states of the various generators available in MATLAB have different sizes and formats, and you can see what they are by looking at the State property of different streams. But I recommend not getting too familiar with, or modifying, the inner workings of these state vectors. Read 'n' write 'em, yes, perhaps even rope 'n' brand 'em, but don't try and understand 'em.

### Where Not To Do Any Of This

Sometimes, discretion is the better part of valor. Be careful to understand why and when you do any of this. Remember, resetting or replacing the default stream, or writing to its state, or jumping to a substream affects all subsequent calls to rand, randn, and randi, and is probably not something you want to do deep in your code - too easy to forget that it is in there. Replacing the default stream, especially, is probably not something you need to do a lot of.

### Next Time

We've seen four ways to reproduce results from MATLAB's random number generators.

• Resetting a stream
• Creating a new stream with a fixed seed
• Substreams
• Explicitly saving and restoring the generator state

But sometimes what's needed is the "opposite of reproducibility" - you want to make sure that different runs of a simulation use different random inputs, because you want to be able to assume that the different runs are statistically independent. Until next time ...

### Other Situations?

Can you think of any cases where you've needed to reproduce random numbers that can't be handled by the examples I've shown? Let me know here.

Get the MATLAB code

Published with MATLAB® 7.7

Iain replied on : 1 of 26

This is very welcome! I often need to “push and pop” the seeds of random number generators. The simplest reason is reproducibility/debugging. Sometimes the reasons are more complex: the natural way to implement some algorithms (e.g. http://dbwilson.com/exact/ ) requires extensive and intricate tracking of pseudo-random seeds.

For more mundane reasons I recently wanted a robust way of returning Matlab’s generators to their state at a recorded time. That is, I wanted to do this:

rand_resetter = make_rand_resetter();
% … “stuff” …
rand_resetter();
% Now random numbers are generated as though “stuff” didn’t happen.
% Even if “stuff” changed the seed and/or generator.

This was made complicated because it didn’t seem possible to ask Matlab (directly) which generator it’s currently using. The make_rand_resetter() function I ended up with is a horrible hack — http://www.cs.toronto.edu/~murray/tmp/mrng/ — because (among other reasons) it has to do a little experiment to infer what the current generator is(!). Sadly, for backwards compatibility, I’ll probably end up using this hack for some time to come.

thomas savarino replied on : 2 of 26

I’m interested in monte carlo applications. If I execute
a function in 32 and 64 bits, can I expect to see the
same random numbers? I can’t even decide if this is
important. What is important to me is that the statistics
of the result be the same for 32 and 64 bit executions as
the sample size gets large.
what do you think?
best regards
tom savarino

Peter Perkins replied on : 3 of 26

Tom, everything in MATLAB is double precision unless you say otherwise, so yes, you get the same random numbers regardless of the platform you’re running on. There is a (new) argument to the rand/randn/randi functions to specify a class, just like you can in ones or zeros. But even if you ask rand for ‘single’ output, it’s as if you had created them in ‘double’ and cast — same values.

Peter Perkins replied on : 4 of 26

Iain wrote:

> This was made complicated because it didn’t seem
> possible to ask Matlab (directly) which generator it’s
> currently using.

Yes, that was one of the main motivations of the new RandStream class.

> Sadly, for backwards compatibility, I’ll probably end
> up using this hack for some time to come.

If by backwards compatibility, you mean that you want the same random values as you used to get, rest assured that the old generators are still in there, and still work as they always have. Check out the doc section on backwards compatibility — you may find that the “legacy stream” is a big help for your make_rand_resetter, it will allow you to see which of those old generators is active. And you may find it possible to use one of the “new style” streams, but with one of the earlier generators. Again, check out the doc.

Jessee replied on : 5 of 26

I once made the mistake of setting the seed/state of Matlab’s random number generator to the iteration number of a Monte Carlo simulation. The problem with doing that is that there’s no guarantee that the Monte Carlo iterations are statistically independent. It is especially not-independent when the the first call to randn is scalar, for example try the following:

for i = 1:NumMC
randn('state',i);
bias(i) = randn(1);
...
end
plot(bias)


My hack at fixing this problem was to “spin-up” the random number generator by calling randn(1000) before using any output from randn. E.g.:

for i = 1:NumMC
randn('state',i)
randn(1000);
bias(i) = randn(1);
...
end


I know this is not the best solution, but it was the best I could come up with at the time. With the new RandomStreams, since Substreams are statistically independent, would a better implementation be the following?

for i = 1:NumMC
stream = RandStream('mt19937ar');
RandStream.setDefaultStream(stream);
stream.Substream = i;

bias(i) = randn(1);
...
end

Peter Perkins replied on : 6 of 26

> With the new RandomStreams, since Substreams are
> statistically independent, would a better implementation
> be the following?
>
> for i = 1:NumMC
> stream = RandStream(‘mt19937ar’);
> RandStream.setDefaultStream(stream);
> stream.Substream = i;
>
> bias(i) = randn(1);
> …
> end

Jessee, as I said in the blog, you probably don’t want to be creating streams and replacing the default stream a lot. My first question would be, “Why do you want to control the sequence of random numbers at all?” If the answer is that you want easy reproducibility of each individual iteration, for debugging or whatever, then by all means use substreams as described my blog post. Otherwise, you most likely want to just draw values from rand and leave the default stream alone.

Take these two lines

stream = RandStream(‘mt19937ar’);
RandStream.setDefaultStream(stream);

out of the loop, and do them once, if at all. They would do exactly the same thing in each iteration anyway. You definitely don’t need a new stream at each iteration.

Iain replied on : 7 of 26

Thanks for the reply Peter. I’ll certainly look into the docs when I get a chance.

By backwards compatibility, I meant that I like my code to run when I give it to other people. My make_rand_resetter will have to fall back to its existing code on older versions of Matlab (and Octave).

R replied on : 8 of 26

Is there a way of generating non-uniform distribution numbers easily. For instance I would like to generate a Maxwell-Boltzman distribution. Can I just give rand a function I’d like it to morph to?

Iain replied on : 9 of 26

The generic way of generating from a non-uniform distribution is to derive the inverse of the cumulative distribution function (cdf). Then you just do:

inv_cdf_for_your_dist(rand)

However, particular distributions may have special tricks that are easier to code. For the Maxwell–Boltzmann distribution you may want to just do sum(randn(3,1),1). For a whole book (available online) of tricks to convert from rand to other distributions see:

http://cg.scs.carleton.ca/~luc/rnbookindex.html

Iain replied on : 10 of 26

[ I meant sqrt(sum(randn(3,1).^2,1)) ]

Noam replied on : 11 of 26

Hi Peter,
Thank you for the clear explanations.
There are certain situations where each iteration in a simulation uses many random numbers. For the most part, I only need to reproduce the run from the beginning of an iteration, so saving the seed before each iteration is sufficient. However, sometimes I notice that something interesting happened late in the iteration (I only “look” at the state of the simulation after each iteration), and it would be useful for me to start with the last seed and go BACKWARD, ie. generating the LAST 1000 random numbers before the end of the iteration. Right now, to do this I rerun the last iteration in a more verbose mode, and check what happened towards the end. But since each iteration can be quite time consuming, it would be nice to be able to simply reverse the stream. Is that possible?
Thanks,
Noam

Peter Perkins replied on : 12 of 26

Noam, I’m not exactly sure what you’re describing. I would think that to reproduce something that happened “late” within an iteration, you’d have to start at the beginning of that iteration. If somehow that’s not the case, it seems like you might be able to use several substreams as “checkpoints” _within_ an iteration, rather than just once at the beginning.

Amir replied on : 13 of 26

Thanks for all the information. I have a question that I hope you can answer me:

Is there any difference between the following two cases?

A) x1 = [rand(1) ; rand(2) ; rand(3)];

B) x2 = rand(3,1);

In other words, is the statistical distributions of the random numbers is different when you generate them all at once using rand(m,n) or generate them one after another using rand(n) but for m*n times.

Amir replied on : 14 of 26

oops! I am sorry there was a typo. The correct form of my question is

A) x1 = [rand(1) ; rand(1) ; rand(1)];

B) x2 = rand(3,1);

Loren replied on : 15 of 26

Amir-

You will get the same answers either way, assuming you start at the same point in the RNG. No difference at all.

–loren

Joe Pohedra replied on : 16 of 26

I want to get different normal distributions for several simulation runs. I’m using this code:
%initialize the random number generator
RandStream.setDefaultStream(RandStream(‘mt19937ar’,'seed’,sum(100*clock)));
%save the state of the random number stream to allow repeating results later
defaultStream = RandStream.getDefaultStream;
savedState = defaultStream.State;
save(‘RandState’, ‘savedState’);
%size distribution
Wmean = [2.65 2.75 2.85];
Wstd = [0.05 0.05 0.05];
W = repmat(Wmean,1000,1) +…
repmat(Wstd,1000,1).*randn(1000,size(Wmean,2));

Later, I try to repeat one of the simulations using:
%commands to restore the random number stream state from the saved mat file
defaultStream.State = savedState;
%size distribution
Wmean = [2.65 2.75 2.85];
Wstd = [0.05 0.05 0.05];
W = repmat(Wmean,1000,1) +…
repmat(Wstd,1000,1).*randn(1000,size(Wmean,2));

But I do not get the same W distributions. What am I doing wrong?

Also, note that the help for RandStream says that the Seed must be an integer. But sum(100*clock) is not an integer.
Thanks,
Joe

Peter Perkins replied on : 17 of 26

Joe, when I run that code I get what I expect – the first W is the same as the second. You haven’t said what you’re doing between these two code snippets, but if you’re not getting what I get, then presumably that’s where to look. Here’s what I suspect happened:

You created defaultStream by calling getDefaultStream. But even though you named it “defaultStream” doesn’t mean that someone can’t change the default stream out from under you. Your defaultStream will remain a valid stream, but not necessarily the default stream. I suspect that you ran code (a doc example?) that had something like “rand(‘state’,0)” in it. That will change the default stream so that your defaultStream will no longer be the thing that the rand function uses.

Yes, the help says that the seed must be an integer. But over the years MATLAB users have grown accustomed to typing sum(100*clock), and there didn’t seem to be any point in requiring anyone to now start typing round(sum(100*clock)). If you do what the help says, you’ll be fine. But if you deviate slightly because of historical reasons, you’ll get something sensible (and consistent with behavior in the older syntax).

Joe Pohedra replied on : 18 of 26

I believe I found the answer to my question about repeating the random sequence used to generate distributions. In addition to saving and restoring the State, I should also save and restore the Seed that I use to initialize the random stream.

For the initial distributions, initialize the random stream:
savedSeed = sum(100*clock);
RandStream.setDefaultStream(RandStream(‘mt19937ar’,'seed’,savedSeed));
defaultStream = RandStream.getDefaultStream;
savedState = defaultStream.State;
save(‘RandInit’, ‘savedSeed’, ‘savedState’);

To re-generate the same distributions again later:
RandStream.setDefaultStream(RandStream(‘mt19937ar’,'seed’,savedSeed));
defaultStream = RandStream.getDefaultStream;
defaultStream.State = savedState;

I don’t think I could have worked this out without the benefit of the descriptions and examples shown in the two parts of “New Ways With Random Numbers”.
Thanks,
Joe

Peter Perkins replied on : 19 of 26

Joe, that does solve your problem, but worrying about the seed if you’ve saved the state is entirely unnecessary. You should look into my previous comments — your problem, I believe, was that the default stream changed out from under you, and the second time through you were setting the state of a stream that RAND was no longer using. So yes, creating and getting a new default one solves the problem, but understanding why you were having a problem might be more instructive.

Joe Pohedra replied on : 20 of 26

Thanks Peter,
(I submitted what became comment #18 before I updated the page and saw your reply #17.) By way of further explanation, the reason I am re-producing the distributions is to add to or extend models that they feed, without changing the partial results of the previous simulation. This happens in different Matlab sessions, and/or with intervening independent runs in other directories. I’ll try a few more experiments to better understand when or if restoring the seed is necessary.

Amin replied on : 21 of 26

i have a question:
i want to simulate a formula containing random numbers from gamma distribution and normal distribution
i want to simulate this formula 50000 times
if i use 10000 instead of 50000,are the results different?
if yes,is there any way to have same result?

Peter Perkins replied on : 22 of 26

Amin, I’m afraid that you have not described what you want to do clearly enough. If you are doing some kind of Monte-Carlo simulation, and you run 50,000 trials, and then run 10,000 trials, then of course the two answers will differ.

Kamal Hossain replied on : 23 of 26

I was wondering, I was using random number(rand command) to generate random values. At a point I have to call a function where I am using a fixed ‘random state’ and after the function operation when I am back to the main program, I want to start from the random state where left from the main program. So how can I do that?
I was trying to do this:

clc; clear; close all;
stream = RandStream.getDefaultStream
savedState = stream.State;
for 1=1:100
u1 = rand(1,5)
end

%function call(using fixed random state)
rand(‘state’,11)
x = rand(1,5)
rand(‘state’,125)
y=rand(1,5)

%back to the main program
s= get(stream)
stream.State = savedState;
for j=1:100
u2 = rand(1,5)
end

but the problem is when I come back to the main program I am getting the same random numbers as I get previously.

Peter Perkins replied on : 24 of 26

Kamal, you are running into trouble because you are mixing two different syntaxes, things like

stream = RandStream.getDefaultStream


and things like

rand(’state’,11)


In this particular case, as I read your code, you’re getting and using the default random number stream in your main code, but your function changes the default stream to something else, and that has global effects. So when you get back to your main code, the default stream is no longer what it was when you saved its state, and while

stream.State = savedState;


does indeed reset the stream’s state, the subsequent call to rand DOESN’T USE that stream because the calls to rand inside your function call have changed the default.

I don’t know what you intend

s= get(stream)


to do, but

RandStream.setDefaultStream(stream)


is probably what you meant to do, and would solve the problem.

Some notes:

1) The calls like rand(’state’,11) use an old syntax, one that has not been recommended for several years, and one that you probably don’t want to mix with calls to RandStream methods, not because it won’t work, but because you will get confused.

2) The term “default stream” refers to “the random number stream that rand/randi/randn use by default”, but since RandStream was introduced in 2008, we found that the term is somewhat confusing. So in R2011a, the doc describes this as “the global random number stream”, and the methods RandStream.get/setGlobalStream are now preferred.

3) I recommend that in your function, you create a local stream, and call rand using that to generate numbers. This will not affect the global stream at all. This strategy described in these blog posts.

4) If you are using R2011a, you may find that the new RNG function, described in another blog post here:

http://blogs.mathworks.com/loren/2011/07/07/simpler-control-of-random-number-generation-in-matlab/

is simpler for your needs. In fact, the second help example

http://www.mathworks.com/help/techdoc/ref/rng.html

does exactly what you want.

SAMITHA replied on : 25 of 26

How can I see the current seed in use?

Peter Perkins replied on : 26 of 26

If all you want to do is _see_ it, just displaying the global stream will show you the seed:

>> RandStream.getGlobalStream
ans =
mt19937ar random stream (current global stream)
Seed: 0
NormalTransform: Ziggurat

Note that getGlobalStream is a new name (in R2011a of the getDefaultStream method from earlier releases. If you want to assign the value to a variable, it’s the .Seed property of that stream.

In R2011a and later, there’s a new simpler interface to controlling random numbers, for non-parallel cases:

>> rng
ans =
Type: ‘twister’
Seed: 0
State: [625x1 uint32]

It’s described here : http://www.mathworks.com/help/techdoc/math/bs1qb_i.html

These postings are the author's and don't necessarily represent the opinions of MathWorks.