Documentation |
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 different MATLAB sessions.
All the random number functions, rand, randn, randi, and 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 rand(2,2) returns 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.
Execute the rng('shuffle') command once in your MATLAB session before calling any of the random number functions.
rng('shuffle')
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.
Alternatively, specify different seeds explicitly. For example,
rng(1); A = rand(2,2); rng(2); B = rand(2,2);
Arrays A and B are different because the generator is initialized with a different seed before each call to the rand function.
Note: 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. |