MATLAB: How to freeze a random sample

randseed

I need to generate a random sample between (0,1) and freeze it so that when I run the program again it generates the same "random" sample. Matlab help gave me:
% Save v5 generator state.
st = rand('state');
% Call rand.
x = rand(1,4);
% Restore v5 generator state.
rand('state',st);
% Call rand again and hope
% for the same results.
y = rand(1,4)
First iteration output is: x =
0.59494 0.27395 0.0481 0.83809
y =
0.59494 0.27395 0.0481 0.83809
But second run produces different sequence: x =
0.10254 0.72827 0.4405 0.99719
y =
0.10254 0.72827 0.4405 0.99719
I need it to give me the same results, so the second run should be: x =
0.59494 0.27395 0.0481 0.83809
y =
0.59494 0.27395 0.0481 0.83809
I know this involves using a seed but the help wasn't clear to me. The rng function doesn't work in my version.

Best Answer

Sophia, unless you are using an old version of MATLAB (R2008a or earlier, as I recall) you should not (NOT!) be using any of the rand or randn syntaxes involving the 'seed', 'state', or 'twister' keywords. They continue to work as they have for many years, including allowing you to make the subtle mistake demonstrated in your code and output.
In short, the first line
st = rand('state')
reads the state of a generator that is not currently "active", or at least not unless you have executed a line such as
rand('state',0)
at some earlier point. This is because 'state' does not refer to "the state of the global random number generator", but rather to "the state of the particular generator that used to be MATLAB's default and is still in there if you absolutely insist on asking for it." Even if that mistake is corrected, the code still uses what is an out of date generator algorithm that is no longer recommended. The same is true of 'seed', for an even older and less-recommended generator.
So, as Honglei recommends, if you are using MATLAB R2011a or newer, use the RNG function. All of the reference pages for rand/randn/randi have an example something like this one from rand:
Example 4: Save the settings for the random number generator used by
rand, RANDI, and RANDN, generate 5 values from rand, restore the
settings, and repeat those values.
s = rng
u1 = rand(1,5)
rng(s);
u2 = rand(1,5) % contains exactly the same values as u1
and that's what you want to do. RNG is also described at length here.