I want to create a matrix of 0 and 1, using Numpy package, alternating 0 and 1, of size 8*8
This means:
I want something like this:
np.random.binomial(n=1, p=0.5, size=[64])
#This is the resulta expected but the code doesn't sort the matrix this way
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
#WHAT I DON'T WANT BUT IT IS QUITE SIMILAR
[[1 1 0 1 1 1 0 1]
[0 0 1 0 1 0 1 0]
[0 0 0 1 0 1 0 1]
[0 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[0 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
The thing is this is balanced, but the result is not 0 and 1, in an alternative way.
I want to create a matrix of 0 and 1, using Numpy package, alternating 0 and 1, of size 8*8
This means:
I want something like this:
np.random.binomial(n=1, p=0.5, size=[64])
#This is the resulta expected but the code doesn't sort the matrix this way
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
#WHAT I DON'T WANT BUT IT IS QUITE SIMILAR
[[1 1 0 1 1 1 0 1]
[0 0 1 0 1 0 1 0]
[0 0 0 1 0 1 0 1]
[0 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[0 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
The thing is this is balanced, but the result is not 0 and 1, in an alternative way.
A simple and fast solution is as follows:
a = np.zeros((N,N))
a[::2, 1::2] = a[1::2, ::2] = 1
The second line has two parts. The first selects every other row starting from the first (zeroth) row and every other column starting from the second column. The second part selects every other row starting with the second row and every other column starting with the first column. Both of those are set to 1.
import numpy as np
n = 8
matrix = np.fromfunction(lambda i, j:(i+j) % 2, (n, n), dtype=int)
print(matrix)
np.random.binomial()
won't provide the desired outcome because it generates a truly random distribution.
Instead, you can create such a matrix using array indexing and NumPy's array manipulation functions.
(np.arange(size)+np.random.randint(2))%2
? – chrslg Commented Nov 16, 2024 at 16:57