admin管理员组

文章数量:1435514

I want to create a matrix of 0 and 1, using Numpy package, alternating 0 and 1, of size 8*8

This means:

  • Along each row, the values alternate between 0 and 1.
  • Along each column, the values also alternate between 0 and 1.

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:

  • Along each row, the values alternate between 0 and 1.
  • Along each column, the values also alternate between 0 and 1.

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.

Share Improve this question edited Dec 18, 2024 at 20:58 khelwood 59.4k14 gold badges89 silver badges115 bronze badges asked Nov 16, 2024 at 16:31 Javier HernandoJavier Hernando 3682 silver badges12 bronze badges 1
  • So something like (np.arange(size)+np.random.randint(2))%2? – chrslg Commented Nov 16, 2024 at 16:57
Add a comment  | 

3 Answers 3

Reset to default 3

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.

本文标签: numpyHow to generate a matrix in Python with 0 and 1 alternatively sortedStack Overflow