【问题标题】:Calculate sum of all directly surrounding elements to some element in matrix计算所有直接周围元素与矩阵中某个元素的总和
【发布时间】:2021-11-23 10:56:40
【问题描述】:

我要计算所有直接包围的元素与矩阵中某个元素的总和。

[ [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9] ]

这样sum_neighbours(matrix[0][0]) == 11sum_neighbours(matrix[1][1]) == 40

问题只是我是初学者,我不知道如何让 sum_neighbours 计算某个数字有多少邻居。 我想我可以写 if-elif-else-statement 然后给出矩阵中每个值具有的特定数量的邻居,但肯定有更有效的方法来做到这一点? 否则它只能计算 3 x 3 矩阵的邻域之和。

【问题讨论】:

标签: python matrix sum


【解决方案1】:

一个不错的方法是使用 numpy 和卷积:

import numpy as np
from scipy.signal import convolve2d
a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

convolve2d(a, [[1,1,1],[1,0,1],[1,1,1]], mode='same')
#                top    center  bottom

输出:

array([[11, 19, 13],
       [23, 40, 27],
       [17, 31, 19]])

或者:

convolve2d(a, np.ones((3,3)), mode='same')-a
# this sums the neighbours + the center
# so we need to subtract the initial array
在更大的数组上的示例并忽略左上角的邻居

这只是为了向你展示在使用卷积时执行类似操作是多么容易

a = np.arange(5*6).reshape((5,6))
# array([[ 0,  1,  2,  3,  4,  5],
#        [ 6,  7,  8,  9, 10, 11],
#        [12, 13, 14, 15, 16, 17],
#        [18, 19, 20, 21, 22, 23],
#        [24, 25, 26, 27, 28, 29]])

convolve2d(a, [[0,1,1],[1,0,1],[1,1,1]], mode='same')
array([[  7,  15,  19,  23,  27,  25],
       [ 20,  42,  49,  56,  63,  52],
       [ 44,  84,  91,  98, 105,  82],
       [ 68, 126, 133, 140, 147, 112],
       [ 62, 107, 112, 117, 122,  73]])

【讨论】:

    【解决方案2】:

    如果您想在没有任何导入的情况下实现这一点(基本假设是您已经检查过您有一个格式正确的列表/矩阵列表,即所有行都具有相同的长度):

    # you pass the matrix and the (i,j) coordinates of the element of interest
    # This select the "matrix" around i,j (flooring to 0 and capping to
    # the number of elements in the list - this is for the elements on the edge
    # of the matrix)
    def select(m, i, j):
        def s(x, y): return x[max(0,y-1):min(len(x),y+1) + 1]
        return [s(x, j) for x in s(m, i)]
    
    def sum_around(m, i, j, excluded = True):
        # this sums all the elements within each list and compute the 
        # grand total. It then subtracts the element in (i,j) if 
        # excluded = True (which is the default behaviour and what you want here) 
        return sum([sum(x) for x in select(m, i, j)]) - (m[i][j] if excluded else 0)
    
    m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    print(sum_around(m, 0, 0)) # prints 11
    
    print(sum_around(m, 1, 1)) # prints 40
    

    【讨论】:

      猜你喜欢
      • 2011-01-17
      • 1970-01-01
      • 2021-11-30
      • 2018-09-15
      • 2017-04-18
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多