How to generate same random number sequence in Octave
In this lesson I'll explain how to get the same sequence of random values when you start Octave
How does random number generation work? Random numbers are generated from a predefined list of pseudo-random numbers according to a statistical distribution. Unlike Matlab, Octave initializes the sequence at session startup using the computer clock as a key. So the sequence of random numbers is always different.
To generate the same sequence of random numbers, save the state of the sequence and assign it to a variable.
>> x=rand("state");
Set the state of the rand function via the variable x
>> rand("state",x);
Now Octave uses the state of the sequence saved in the variable x.
For example, make a random matrix
>> randi(3,3)
ans =
1 3 1
1 2 3
1 2 3
Set random state to the variable x.
>> rand("state",x);
Now generate another random matrix
>> randi(3,3)
ans =
1 3 1
1 2 3
1 2 3
The result is the same random matrix
This way you can use the same sequence of random numbers when starting a program.
Note. When you start a new session you have to repeat the same commands. Alternatively, to have the same random number sequence in each session, you must save the state to a file.
To stop using the same random number sequence, type rand("state","reset")
>> rand("state","reset")