2

I want to generate a random n x n binary matrix using NumPy, where:

  • each value is either 0 or 1
  • every row sums up to 1
  • every column sums up to 1

For example, a valid matrix might be

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

while an invalid one is

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

I tried doing the following, but I couldn't figure out how to shuffle the values in each column using a unique index. How do I generate a matrix that adheres to the above constraints?

N = 10
a = np.zeros((N,N))
a[0,:] = 1

2 Answers 2

6

Create an n by n identity matrix, and then shuffle all of the rows. The identity matrix is a binary matrix where each row and column sums to one, and shuffling the rows preserves this property:

n = 5
result = np.identity(n)
np.random.shuffle(result)
print(result)

This will output something like:

[[0. 1. 0. 0. 0.]
 [0. 0. 0. 0. 1.]
 [0. 0. 0. 1. 0.]
 [1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0.]]
Sign up to request clarification or add additional context in comments.

Comments

4

Use np.random.permutation to create random column indices and then use advanced indexing fill indices with 1s:

N = 10
a = np.zeros((N,N), dtype=int)

a[np.arange(N), np.random.permutation(N)] = 1

a
array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.