Reputation: 45
I need a matrix in python including random number as its elements. But these elements shouldn't be change in multiple run:
myMat=np.random.randint(0, 10, size=(5,5))
[[9 5 1 4 3]
[2 1 5 9 3]
[9 2 7 8 4]
[5 7 2 7 2]
[9 0 8 0 8]]
I need a random matrix just to start my code. After that no change should be happen. I tried '.seed()' method but it looks it doesn't work in case of 2d matrixes.
Upvotes: 1
Views: 166
Reputation: 3318
You could use a list comprehension to cast the arrays to lists, which wouldn't change after initial declaration.
import numpy as np
my_mat = [list(arr) for arr in np.random.randint(0, 10, size=(5,5))]
Edit: I tested this out, and it doesn't appear that the random arrays change after they're initially stored, so casting shouldn't be needed. The following worked for me.
import numpy as np
my_mat = np.random.randint(0, 10, size=(5,5))
print(my_mat)
print()
print(my_mat)
print()
for n, arr in enumerate(my_mat):
for i, arr2 in enumerate(my_mat):
if i == n:
print(arr)
print(arr2)
print()
[[4 6 5 2 1]
[7 5 2 6 6]
[3 6 2 2 1]
[0 6 8 5 4]
[1 5 6 2 4]]
[[4 6 5 2 1]
[7 5 2 6 6]
[3 6 2 2 1]
[0 6 8 5 4]
[1 5 6 2 4]]
[4 6 5 2 1]
[4 6 5 2 1]
[7 5 2 6 6]
[7 5 2 6 6]
[3 6 2 2 1]
[3 6 2 2 1]
[0 6 8 5 4]
[0 6 8 5 4]
[1 5 6 2 4]
[1 5 6 2 4]
Upvotes: 0
Reputation: 177674
np.random.seed()
works. As long as you use the same seed the same matrices will be generated:
>>> import numpy as np
>>> np.random.seed(1)
>>> np.random.randint(0,10,size=(5,5))
array([[5, 8, 9, 5, 0],
[0, 1, 7, 6, 9],
[2, 4, 5, 2, 4],
[2, 4, 7, 7, 9],
[1, 7, 0, 6, 9]])
>>> np.random.randint(0,10,size=(5,5))
array([[9, 7, 6, 9, 1],
[0, 1, 8, 8, 3],
[9, 8, 7, 3, 6],
[5, 1, 9, 3, 4],
[8, 1, 4, 0, 3]])
>>> np.random.seed(1) # reset to same seed
>>> np.random.randint(0,10,size=(5,5)) # same first matrix
array([[5, 8, 9, 5, 0],
[0, 1, 7, 6, 9],
[2, 4, 5, 2, 4],
[2, 4, 7, 7, 9],
[1, 7, 0, 6, 9]])
>>> np.random.randint(0,10,size=(5,5)) # same second matrix
array([[9, 7, 6, 9, 1],
[0, 1, 8, 8, 3],
[9, 8, 7, 3, 6],
[5, 1, 9, 3, 4],
[8, 1, 4, 0, 3]])
To maintain over multiple runs of a script you'll have to save the initial seed in a file or something. For example on the first run check for the existence of the file, pick a seed and save it. Later runs the file exists and initialize the seed from the file.
Upvotes: 2