I need to find the sum of all the 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]]
sum of nearest elements of cell [0][0]
is 3
at [1][0]
is 5
and at [1][1]
is 8
Is there a python lib to find the sum of all the elements next to the given cell?
If you don't mind the dependency on scipy, you can use scipy.ndimage.convolve
, as follows:
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]])
You can use slicing and np.sum
to calculate the sum of a particular 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
Notice that the max
is there because negative starting indexes trigger different slicing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With