recipes : programming : Generating random numbers in a repeatable way

Problem

You want to repeatably generate the same sequence of random numbers.

Solution

Random number generators produce the numbers based upon a "seed." If you set the seed to the same value each time you run rand then you will get the same random numbers each time.

rand('seed',101)
rand(1,4)

ans =

    0.8038    0.5089    0.3899    0.5996

%And again
rand('seed',101)
rand(1,4)

ans =

    0.8038    0.5089    0.3899    0.5996

%But if you now don't reset the seed, you will get different numbers:
rand(1,4)

ans =

    0.8008    0.6328    0.7128    0.8866

Discussion

Each time you start MATLAB the seed for the random number generator is the same and this may cause problems for certain applications. An easy way of solving this is to set the seed to current time: rand('seed',sum(100*clock()))

There are various reasons why you might want to set the random seed to the same value each time. For example, you might be adding a random component to a plot and you want the appearance of the plot to be reproducible whilst you're developing it. You might have an analysis that involves adding a random component and you want someone else at a later date to be able to run the analysis exactly the same way you did.