【问题标题】:How to create a matrix of the sums of nearby numbers in a matrix in python without use of numpy如何在不使用numpy的情况下在python中的矩阵中创建附近数字之和的矩阵
【发布时间】:2018-10-17 11:35:23
【问题描述】:

我有一个 x x x 矩阵,如下所示

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

还有一个范围

range_of_addition=1

然后我将创建一个新矩阵,它将矩阵中元素范围内的所有数字相加。

new_matrix=[[12,21,16],[27,45,33],[24,39,28]]

第一个元素是 12,因为它是 1+2+4+5。同样,中心元素是原始矩阵中所有元素的总和,因为所有元素都在范围内。

如何创建一个与原始矩阵大小相同但每个元素都是自身和自身指定范围内的所有元素之和的矩阵?

【问题讨论】:

  • 请提供您预期的输出矩阵
  • 我不确定我是否理解。创建矩阵有什么不明白的地方?
  • @MihaiAlexandru-Ionut 我已经更新了
  • @PeterWood 我想创建一个像现在更新的输出
  • 如何获得21

标签: python python-3.x math matrix


【解决方案1】:

不使用 numpy (我认为它比使用 numpy 灵活一点,但是我不知道 numpy 足以给出正确的意见):

def matrix_get(matrix, position, offset):
    if position[0]+offset[0] < 0 or position[1]+offset[1] < 0:
        return 0
    # I'm using try/except to catch out of range error; in which case, this will return 0
    try:
        return matrix[position[0]+offset[0]][position[1]+offset[1]]
    except:
        return 0

new_matrix = []
row = []
total = 0

for r, a in enumerate(matrix):
    for c in range(len(a)):
        for x in range(-1, 2):
            for y in range(-1, 2):
                total += matrix_get(matrix, (r, c), (y, x))
        row.append(total)
        total = 0
    new_matrix.append(row)
    row = []

print(new_matrix)
# [[12, 21, 16], [27, 45, 33], [24, 39, 28]]

【讨论】:

    【解决方案2】:

    这是卷积任务。 输入:

    a = np.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]])
    
    conv_filter = np.array([[1,1,1],
                            [1,1,1],
                            [1,1,1]])
    

    代码:

    import numpy as np
    
    def conv2d(a, f):
        b = np.zeros([a.shape[0]+int(f.shape[0]/2)*2,a.shape[1]+int(f.shape[0]/2)*2])
        for i in range(1,b.shape[0]-int(f.shape[0]/2)):
            for j in range(1,b.shape[1]-int(f.shape[0]/2)):
                b[i][j] = a[i-1][j-1]
        s = f.shape + tuple(np.subtract(b.shape, f.shape) + 1)
        strd = np.lib.stride_tricks.as_strided
        subM = strd(b, shape = s, strides = b.strides * 2)
        return np.einsum('ij,ijkl->kl', f, subM)
    
    conv2d(a,conv_filter)
    

    输出:

    array([[ 12.,  21.,  27.,  33.,  24.],
           [ 33.,  54.,  63.,  72.,  51.],
           [ 63.,  99., 108., 117.,  81.],
           [ 93., 144., 153., 162., 111.],
           [ 72., 111., 117., 123.,  84.]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 2018-01-18
      相关资源
      最近更新 更多