numpymatlabnumpy-random

How to restore matlab random generator state into numpy?


I can save the state of matlab random generator with the following code

seed = 10;
rng(seed, 'twister');
%... random functions that don't need to be reproduced%

s = rng;
s.Type
s.Seed
s.State
save('rand_state.mat', 's');

%... random functions that need to be reproduced%

How would you import the state of the Mersenne Twister into numpy so that it generates the same random numbers after it was saved?

Just using np.random.RandomState(seed) does not take into account that the state of the twister was modified by the subsequent random calls before it was saved.


Solution

  • np.random.RandomState has a function set_state() that takes the input state = ('MT19937', keys, pos)

    The only gotcha is that matlab saves pos as the last element of State. The rest are the keys that set_state expects.

    rng = np.random.RandomState(s['Seed'])
    rng.set_state("MT19937", s['State'], s['State'][-1])
    

    I learned the hard way that that matlab and python use different transformations to convert random draws from [0,1) into integers or normal variates. So one will have to write custom functions for ints and normals in matlab, if that needs to be replicated in python.