如何在大矩阵中找到小矩阵的最佳“匹配”? 例如:
small=[[1,2,3],
[4,5,6],
[7,8,9]]
big=[[2,4,2,3,5],
[6,0,1,9,0],
[2,8,2,1,0],
[7,7,4,2,1]]
匹配被定义为矩阵中数字的差异,因此位置 (1,1) 的匹配就好像小矩阵中的数字 5 位于大矩阵中的数字 0 上(因此小矩阵中的中心数字在坐标 (1 ,1) 大矩阵。
位置(1,1)的匹配值为: m(1,1)=|2−1|+|4−2|+|2−3|+|6−4|+|0−5|+|1−6|+|2−7|+| 8−8|+|2−9|=28
目标是在这些矩阵中找到可能的最小差异。
小矩阵的行数和列数总是奇数,所以很容易找到它的中心。
最佳答案
您可以遍历可行的行和列,并将 big
的切片与 small
压缩以计算差异之和,并使用 min
找出差异中的最小值:
from itertools import islice
min(
(
sum(
sum(abs(x - y) for x, y in zip(a, b))
for a, b in zip(
(
islice(r, col, col + len(small[0]))
for r in islice(big, row, row + len(small))
),
small
)
),
(row, col)
)
for row in range(len(big) - len(small) + 1)
for col in range(len(big[0]) - len(small[0]) + 1)
)
或在一行中:
min((sum(sum(abs(x - y) for x, y in zip(a, b)) for a, b in zip((islice(r, col, col + len(small[0])) for r in islice(big, row, row + len(small))), small)), (row, col)) for row in range(len(big) - len(small) + 1) for col in range(len(big[0]) - len(small[0]) + 1))
返回:(24, (1, 0))
关于python - python中的矩阵匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53287262/