Home > Enterprise >  how to fill zeros matrix with ones based on a list of values
how to fill zeros matrix with ones based on a list of values

Time:11-07

I have k = [3, 2, 0, 1] and A array filled with zeros. I want to fill A with ones such that each row sums up to a value in k

k = [3, 2, 0, 1]
A = np.zeros((n, n), dtype=int)
for i in k:
   A = np.random.randint(2, size=i)

the expected output:

([[1., 0., 1., 1.],
     [0., 1., 1., 0.],
     [1., 0., 1., 0.],
     [0., 0., 0., 0.])

I appreciate it

CodePudding user response:

You may use numpy.random.choice

numpy.random.choice

Generates a random sample from a given 1-D array

import numpy as np

k = [3, 2, 0, 1]
n = 4
A = np.zeros((n, n), dtype=int)

for idx, row_sum in enumerate(k):
    x = np.random.choice(n, row_sum, replace=False)
    A[idx, x] = 1

print(A)

output will be like

[[1 0 1 1]
 [1 1 0 0]
 [0 0 0 0]
 [0 0 0 1]]

CodePudding user response:

I guess you can fill the rows by assigning the values like this.

A[i, : k[i]] = 1

Or

A[i, np.random.choice(n, k[i], replace=False)] = 1 # Fill the row with ones in random positions

So the working example should look like this:

import numpy as np

k = [3, 2, 0, 1]
n = len(k)
A = np.zeros((n, n), dtype=int)

for i in range(n):
    A[i, np.random.choice(n, k[i], replace=False)] = 1 # ones in random positions

The output of A

[[1 1 0 1]
 [1 0 0 1]
 [0 0 0 0]
 [0 0 0 1]]
  • Related