如何制作大小为 2 个单元格的矩阵?
How to make a matrix with a size of 2 cells?
如何制作一个大小为2个单元格的矩阵?
我需要一个像棋盘一样的矩阵,但在一个地方有两个单元格
矩阵的大小应为 n X m,单元格大小为 2 X 2
我写了这段代码:
[在]:
def mat(n, m):
sq = np.zeros((n, m))
sq[::2, 1::2] = 1
sq[1::2, ::2] = 1
a = str(sq).replace('.', '')
print(a)
mat(10, 10)
[Out]:
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
但我需要这样的:
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
你的想法是正确的;您只需要稍微修复一下索引即可。您需要使用两个切片和四个步骤来创建“拿两个,跳过两个”模式,而不是使用 2 步:
sq[::4, 2::4] = 1
sq[::4, 3::4] = 1
sq[1::4, 2::4] = 1
sq[1::4, 3::4] = 1
sq[2::4, ::4] = 1
sq[2::4, 1::4] = 1
sq[3::4, ::4] = 1
sq[3::4, 1::4] = 1
这输出:
[[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]]
如何制作一个大小为2个单元格的矩阵?
我需要一个像棋盘一样的矩阵,但在一个地方有两个单元格
矩阵的大小应为 n X m,单元格大小为 2 X 2 我写了这段代码: [在]:
def mat(n, m):
sq = np.zeros((n, m))
sq[::2, 1::2] = 1
sq[1::2, ::2] = 1
a = str(sq).replace('.', '')
print(a)
mat(10, 10)
[Out]:
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
但我需要这样的:
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
你的想法是正确的;您只需要稍微修复一下索引即可。您需要使用两个切片和四个步骤来创建“拿两个,跳过两个”模式,而不是使用 2 步:
sq[::4, 2::4] = 1
sq[::4, 3::4] = 1
sq[1::4, 2::4] = 1
sq[1::4, 3::4] = 1
sq[2::4, ::4] = 1
sq[2::4, 1::4] = 1
sq[3::4, ::4] = 1
sq[3::4, 1::4] = 1
这输出:
[[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]]