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 |3 Answers
Reset to default 3A 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
版权声明:本文标题:numpy - How to generate a matrix in Python with 0 and 1 alternatively sorted - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745652225a2668496.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
(np.arange(size)+np.random.randint(2))%2
? – chrslg Commented Nov 16, 2024 at 16:57