The sum of 8 neighbors in a 2d array

I need to find the sum of all neighboring elements of a cell, say getsumofneighbors(matrix, i, j) :

 'M*N matrix' [[0 1 0] [2 0 1] [0 4 0] [0 0 0]] 

the sum of the closest elements of the cell [0][0] is 3

at [1][0] is 5

and when [1][1] is equal to 8

Is there any python lib to find the sum of all elements next to a given cell?

+5
source share
4 answers

If you don't mind scipy dependency, you can use scipy.ndimage.convolve as shown below:

 In [475]: a Out[475]: array([[0, 1, 0], [2, 0, 1], [0, 4, 0], [0, 0, 0]]) In [476]: kernel Out[476]: array([[1, 1, 1], [1, 0, 1], [1, 1, 1]]) In [477]: from scipy.ndimage import convolve In [478]: c = convolve(a, kernel, mode='constant') In [479]: c Out[479]: array([[3, 3, 2], [5, 8, 5], [6, 3, 5], [4, 4, 4]]) 
+8
source

You can use slicing and np.sum to calculate the sum of a specific region:

 def getsumofneighbors(matrix, i, j): region = matrix[max(0, i-1) : i+2, max(0, j-1) : j+2] return np.sum(region) - matrix[i, j] # Sum the region and subtract center 

Note that max exists because negative leading indexes trigger different slices.

+2
source

Decision

 def sum_neighbors(A, i, j): rows, columns = A.shape r0, r1 = max(0, i-1), min(rows-1, i+1) c0, c1 = max(0, j-1), min(columns-1, j+1) rs = list({r0, i, r1}) cs = [[c] for c in list({c0, j, c1})] return A[rs, cs].sum() - A[i, j] 

Explanation

Slice A on the line before and after i with the column before and after j . Take the amount and subtract the cell in i , j . All other codes are for edge processing.

Demonstration

 import numpy as np mxn = np.array([[0, 1, 0], [2, 0, 1], [0, 4, 0], [0, 0, 0]]) for i, j in [(0, 0), (1, 0), (1, 1)]: s = "sum of neigbors for i={} and j={} is {}" print s.format(i, j, sum_neighbors(mxn, i, j)) sum of neigbors for i=0 and j=0 is 3 sum of neigbors for i=1 and j=0 is 5 sum of neigbors for i=1 and j=1 is 8 
0
source

Just created this function that will complete the task.

 def sumofnieghbors(MatrixObj, indexR, indexC): upperleft = 0 if not (indexR < 1) or (indexC < 1): upperleft = MatrixObj[indexR - 1][indexC - 1] upper = 0 if not (indexR < 1): upper = MatrixObj[indexR - 1][indexC] upperright = 0 if not ((indexR < 1) or (indexC >= NbofCol)): upperright = MatrixObj[indexR - 1][indexC + 1] right = 0 if not (indexC >= NbofCol): right = MatrixObj[indexR][indexC + 1] rightdown = 0 if not ((indexR >= NbofRow) or (indexC >= NbofCol)): rightdown = MatrixObj[indexR + 1][indexC + 1] down = 0 if not (indexR >= NbofRow): down = MatrixObj[indexR + 1][indexC] leftdown = 0 if not ((indexR >= NbofRow) or (indexC < 1)): leftdown = MatrixObj[indexR + 1][indexC - 1] left = 0 if not (indexC < 1): left = MatrixObj[indexR][indexC - 1] return (upperleft + upper + upperright + right + rightdown + down + leftdown + left) 
-1
source

All Articles