0

I need to reproduce many pseudo-random matrices generated with Matlab's randi function for fixed seeds.

To give a simple example, I want to reproduce

>> rng(2);
>> randi([-10, 10], 4, 4)

ans =

    -1    -2    -4    -8
   -10    -4    -5     0
     1    -6     3    -7
    -1     3     1     6

According to the docs, Matlab's randi uses the Mersenne Twister random number generator. Here's what I tried so far with numpy:

In [2]: np.random.seed(2)

In [3]: np.random.randint(-10, 11, size=(4,4))
Out[3]:
array([[-2,  5,  3, -2],
       [ 1,  8,  1, -2],
       [-3, -8,  7,  1],
       [ 5, 10, 10, -5]])
In [5]: from numpy.random import MT19937

In [6]: from numpy.random import RandomState, SeedSequence

In [7]: rs = RandomState(MT19937(SeedSequence(2)))

In [8]: rs.randint(-10, 11, size=(4,4))
Out[8]:
array([[-10,   0,  -6,  -3],
       [ -2,   8, -10,  -8],
       [ -1,  -6,  10,   6],
       [  9,   1,  -6,   0]])

Any ideas?

I'm aware that I could export the matrices from matlab to Python, but I want to reproduce the same pseudo-random numbers.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Ronaldinho
  • 375
  • 1
  • 12
  • 1
    In general, the best way to "sync" PRNGs between two programs in different languages is to implement the same PRNG in both languages. Here is one example: https://stackoverflow.com/questions/59829276/how-to-sync-a-prng-between-c-unity-and-python/59831276#59831276 – Peter O. Apr 05 '21 at 12:55
  • We don't know how the 'raw' random values are translated into integers, particularly the sequence produced for a matrix. – hpaulj Apr 05 '21 at 15:55

0 Answers0