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
reads the state of a generator that is not currently "active", or at least not unless you have executed a line such as
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)
and that's what you want to do. RNG is also described at length here.
Best Answer