How to set a limited defined random values in numpy matrix

How to set a limited random values by amount and range in nupmy matrix ?

Means instead :

random_matrix = np.random.rand(5, 5)
[[0.38555213 0.96454126 0.91586422 0.92638243 0.85516641]
[0.64717218 0.2716665  0.70945594 0.74754943 0.48870502]
[0.23381316 0.01992578 0.86749684 0.85797792 0.19308509]
[0.63565231 0.7056163  0.69110815 0.73506642 0.804646  ]
[0.35512519 0.54900446 0.66311323 0.04899527 0.49349834]]

the wanted setting for example is 3 random integers between the range 1-5 in a null matrix :

0,0,0,4,0
0,0,0,0,0
0,1,0,0,0
0,0,0,3,0
0,0,0,0,0

Thanks in advance

Answer

If i understand the question correctly, you want to create a matrix that is zero in all places except for 3 random indices that will have a random value between the range 1-5.

For this i would suggest doing:

null_matrix = np.zeros((5,5), dtype=np.int32)

rng = np.random.default_rng()
x = rng.choice(5, size=3, replace=False)
y = rng.choice(5, size=3, replace=False)

null_matrix[x,y] = rng.choice(np.arange(1,5), 3)
print(null_matrix)

Output:

array([[0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [4, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 2]], dtype=int32)