python - 如何根据 python 中提供的 0 和 1 矩阵生成矩阵组合?

标签 python arrays numpy matrix

我有一个 3x3 的 0 矩阵和一个 2x2 的 1 矩阵:

a = np.zeros((3, 3), dtype=int)
b = np.ones((2, 2), dtype=int)
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
array([[1, 1],
       [1, 1]])

我想从 ab 生成所有可能的矩阵组合,如下所示:

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

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

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

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

有什么方法可以快速做到这一点吗?我尝试使用for循环来修改矩阵a的值,但是相当麻烦。任何帮助将不胜感激。

最佳答案

您可以尝试以下操作:

m1, m2 = 4, 4
n1, n2 = 2, 3

a=np.zeros((m1,m2),dtype=int)
b=np.ones((n1,n2),dtype=int)

d1 = m1 - n1 + 1
d2 = m2 - n2 + 1

for i in range(d1):
    for j in range(d2):
        temp = a.copy()
        temp[i:i+n1,j:j+n2] = b
        print(temp)

输出:

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

适用于所有形状的矩阵。

关于python - 如何根据 python 中提供的 0 和 1 矩阵生成矩阵组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65575502/

相关文章:

python - 带有 datashader 的 map 背景 - "Map data not yet available"

python - 使用 Pandas 将多个时间序列行合并为一行

python,从列表中删除字符串中的单词

c - NASM 数组指针操作

python - 在 numpy 数组上使用拟合变换

python - 索引 81 处不支持格式字符 '@' (0x40)

php 将发布数据更改为变量

php - 如何在 PHP POST 中传递数组变量?

python - 在日期时间字段中按小时对 NumPy 数组进行分箱

python - 在 Python 中计算 numpy ndarray 中非 NaN 元素的数量