Generate Random Numbers That Are Different
This example shows how to avoid repeating the same random number arrays when MATLAB® restarts. This technique is useful when you want to combine results from the same random number commands executed at different MATLAB sessions.
All the random number functions,
randperm, draw values from a shared random
number generator. Every time you start MATLAB, the generator
resets itself to the same state. Therefore, a command such as
the same result any time you execute it immediately following startup.
Also, any script or function that calls the random number functions
returns the same result whenever you restart.
One way to get different random numbers is to initialize the generator using a different seed every time. Doing so ensures that you don’t repeat results from a previous session.
rng('shuffle') command once in
your MATLAB session before calling any of the random number functions.
You can execute this command in a MATLAB Command Window, or you can add it to your startup file, which is a special script that MATLAB executes every time you restart.
Now, execute a random number command.
A = rand(2,2);
Each time you call
rng('shuffle'), it reseeds
the generator using a different seed based on the current time.
Frequent reseeding of the generator does not improve the statistical properties of the output and does not make the output more random in any real sense. Reseeding can be useful when you restart MATLAB or before you run a large calculation involving random numbers. However, reseeding the generator too frequently within a session is not a good idea because the statistical properties of your random numbers can be adversely affected.
Alternatively, specify different seeds explicitly in different MATLAB sessions. For example, generate random numbers in one MATLAB session.
rng(1); A = rand(2,2);
Use different seeds to generate random numbers in another MATLAB session.
rng(2); B = rand(2,2);
B are different because the
generator is initialized with a different seed before each call to the
To generate multiple independent streams that are guaranteed to not overlap,
and for which tests that demonstrate independence of the values between streams
have been carried out, you can use
RandStream.create. For more information about generating
multiple streams, see Multiple Streams.