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.

>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

Leave a Reply