Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a 5 by 5 matrix with 5 ones randomly distributed

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))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading