lettura simple

Generating the Same Sequence of Random Numbers in Matlab

In this lesson, I will explain how to generate consistent sequences of random numbers in Matlab.

Why generate consistent random numbers? Random number generation is based on algorithms that extract lists of pseudorandom numbers from seeds, following statistical distributions. The sequence of random numbers varies in each session. However, there are cases where working with the same random numbers is useful, such as when testing a program.

To generate consistent sequences of random numbers, you can save the state of the sequence in a variable.

>> x=rand("state");

This allows you to set the state of the rand() function at the beginning of your script or session using the variable x.

>> rand("state",x);

This Matlab command ensures that you get the same sequence of random numbers every time.

Let me provide you with a practical example.

Generate a matrix of random integers.

>> randi(3,3)
ans =
1 3 1
1 2 3
1 2 3

Now, reload the random number generation into memory using the variable x.

>> rand("state",x);

Then generate another random 3x3 matrix.

>> randi(3,3)
ans =
1 3 1
1 2 3
1 2 3

The two matrices will be identical.

This way, you can generate the same sequence of random numbers multiple times.

Note. To use the same variable x in other sessions or on other computers, I recommend saving the content of the variable in a file on your PC and loading it into Matlab's memory when starting a new session.

Resetting the Sequence of Random Numbers

To reset the sequence of the current state, use 0 as the second parameter.

For example, type rand("state", x) to load the previously saved sequence of random numbers into the variable x.

>> rand("state",x);

Generate a matrix of random integers.

>> randi(3,3)
ans =
1 3 1
1 2 3
1 2 3

Now, type rand("state", 0) to reset the sequence.

>> rand("state",0)

Then generate a 3x3 random matrix.

>> randi(3,3)
ans =
1 3 1
1 2 3
1 2 3

The result will be the same matrix every time.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin