Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: Generate same Random Number sequence

Tags:

random

matlab

I want to use the mersenne twister to generate 'N' random numbers between 10 to 50. I want to be able to generate the same sequence over and over again.

I wrote the following code: (seed = 50, a = 10, b = 50, N = number of required random numbers)

s = rng(seed, 'twister');
r = a + (b-a)*rand(N,1);
rng(s);
r1 = a + (b-a)*rand(N,1);

Now even I print

r1 - r

I don't get zero. I expect to get zero as I have reset the random number generator to it's initial state in the third line of my code.

My question is where am I going wrong?

like image 517
sixtyTonneAngel Avatar asked Jul 02 '26 21:07

sixtyTonneAngel


1 Answers

From the rng documentation:

sprev = rng(...) returns the previous settings of the random number generator used by rand, randi, and randn before changing the settings.

So your s is the previous state, not the set state. Changing things to

rng(seed, 'twister');
s=rng();
r = a + (b-a)*rand(N,1);
rng(s);
r1 = a + (b-a)*rand(N,1);

should produce the desired behavior.

This may seem cumbersome, but it arises since rng is meant to be treated like a toggle: you set your state while storing the previous one for future restoration. After all, immediately resetting the state appears to be more diagnostic than practical.

like image 196
TroyHaskin Avatar answered Jul 05 '26 11:07

TroyHaskin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!