Home > Mobile >  Create a 5 by 5 matrix with 5 ones randomly distributed
Create a 5 by 5 matrix with 5 ones randomly distributed

Time:04-21

Here is the code I have tried. How can I modify it if we just want 5 ones randomly distributed in it?

import numpy as np
mat = np.random.randint(2,size=(5,5))

CodePudding user response:

>>> import numpy as np
>>> import random
>>> mat = np.zeros(5*5)
>>> indices = random.sample(range(5*5), 5)
>>> mat[indices] = 1
>>> mat = mat.reshape(5, 5)
>>> mat
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1.],
       [0., 0., 1., 0., 0.],
       [1., 0., 1., 0., 1.],
       [0., 0., 0., 0., 0.]])

I've explicitly used 5*5. You can put 25 there, or N*M or similar.

You could also use the NumPy random module, but the Python stdlib random module is easy enough to use here.

CodePudding user response:

Since sometime comments may contain excellent answers, but may be hidden from view (or deleted altogether), I'm putting here the solution provided by Michael Szczesny:

>>> mat = np.random.permutation(np.eye(5, dtype=int).ravel()).reshape(5,5)
>>> mat
array([[0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [1, 1, 0, 0, 0],
       [0, 0, 1, 1, 0],
       [0, 0, 0, 0, 0]])
  • Related