How can I generate a Random (N*M) 0's and 1's Matrix in which the sum of each row equals to 10? (in python using numpy)
for example for 10*10(N*M)
matrix we can use:
import numpy as np
np.random.randint(2, size=(10, 10))
but I want sum of each rows equals to 10
CodePudding user response:
This isn't necessarily the most efficient method, but it is concise:
In [29]: rng = np.random.default_rng(121263137472525314065)
In [30]: n_rows = 5
In [31]: n_cols = 20
In [32]: n_ones = 10
In [33]: rng.multivariate_hypergeometric([1]*n_cols, n_ones, size=n_rows)
Out[33]:
array([[0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1],
[0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1],
[1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0]])
CodePudding user response:
Or, allocate arrays of zeroes and ones and shuffle each row:
import numpy as np
n_rows = 5
n_cols = 20
n_ones = 10
arr = np.tile(np.repeat([0, 1], [n_ones, n_cols-n_ones]), (n_rows,1))
# [[0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
# [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
# [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
# [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
# [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]]
np.apply_along_axis(np.random.shuffle, 1, arr) # operates on arr inplace
# [[1 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 1 1]
# [1 0 1 1 0 1 1 0 0 0 1 0 1 0 1 1 0 0 1 0]
# [1 1 0 1 0 0 0 1 0 0 1 1 0 0 1 0 1 1 1 0]
# [1 0 0 1 0 0 0 1 0 0 1 1 0 1 1 0 1 0 1 1]
# [1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 1 1 0 0 0]]
CodePudding user response:
you could sample a random 10 indices for each row
def make_thing(n):
if n <= 10:
return np.ones((10,10))
matrix = np.zeros((n, n))
for row in range(n):
ten_random_index = random.sample(range(n),10)
matrix[row][ten_random_index] = 1
return matrix
or you could predefine a row
row = [1]*10 [0]*(n-10)
matrix = numpy.array([random.sample(row,n) for _ in range(n)])
CodePudding user response:
You could use the below function to get a random matrix with 1s and 0s and row sum equal to 10:
def matrix_generator(n_rows, n_columns):
if n_columns < 10:
print('Number of rows need to be greater than or equal to 10.')
return 0
row_list = [1,1,1,1,1,1,1,1,1,1]
add_columns = n_columns-10
for i in range(add_columns):
row_list.append(0)
matrix = [[]]*n_rows
for i in range(n_rows):
random.shuffle(row_list)
matrix[i] = row_list[:]
random.shuffle(matrix)
return matrix