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

Generate matrices with specific number of a specific entry

I am attempting to create many matrices in Python, each of which is a 4 x 4 matrix. Each matrix is a matrix filled with 0s, but there is an input that randomly enters the number of 8’s that will be put into that matrix. For example, if a 3 is input, then 3 of the 16 entries will be 8s, and the rest will be 0’s.

It would also be helpful to show how this could be looped over a sequence of values, to generate many different matrices. Thank you.

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

>Solution :

Here’s a code snippet to do it for one matrix:

# Create m x n matrix with 0s
a = np.zeros((m,n))

# Get n random indices to replace with 8

x_indices = np.random.choice(a.shape[0], n, replace=False)
y_indices = np.random.choice(a.shape[1], n, replace=False)

# Replace those positions with 8

a[x_index, y_index] = 8

You can loop it over to get many different matrices

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