For each element of a Matrix I want to count the sum of the k-closest cells. From this function
def sum_neighbors(a, radius, row_number, column_number):
A = [[a[i][j] if i >= 0 and i < len(a) and j >= 0 and j < len(a[0]) else 0
for j in range(column_number-1-radius, column_number+radius)]
for i in range(row_number-1-radius, row_number+radius)]
return np.sum(A)
I can do this. For instance, If I have the following matrix
A
array([[1, 8, 2, 2, 8, 2, 4, 2, 6],
[3, 6, 9, 9, 1, 8, 0, 3, 9],
[7, 4, 2, 7, 8, 5, 8, 8, 1],
[8, 3, 2, 3, 6, 9, 9, 1, 6],
[1, 1, 3, 5, 6, 2, 9, 1, 8],
[7, 0, 8, 7, 9, 8, 4, 4, 6],
[1, 8, 5, 4, 7, 4, 8, 7, 0],
[2, 8, 0, 3, 5, 6, 4, 3, 9],
[1, 5, 1, 9, 9, 4, 5, 7, 9]])
I can run the following to get, for each values, the sum of the all the values a radius of 2 cells.
s = np.shape(A)
As = np.zeros(s)
for i in range(0,s[0]):
for j in range(0,s[1]):
As[i][j]=neighbors(A, 2, i, j)
As
array([[ 18., 29., 40., 49., 55., 45., 39., 43., 34.],
[ 29., 42., 60., 77., 81., 75., 75., 73., 56.],
[ 40., 55., 76., 99., 104., 104., 103., 104., 81.],
[ 42., 60., 86., 115., 121., 129., 126., 130., 101.],
[ 40., 64., 95., 125., 131., 147., 140., 139., 109.],
[ 40., 60., 86., 122., 126., 148., 149., 144., 108.],
[ 39., 57., 79., 112., 122., 136., 134., 141., 108.],
[ 34., 51., 79., 115., 127., 135., 140., 144., 108.],
[ 32., 46., 69., 99., 110., 110., 117., 118., 88.]])
However, for large matrices the loop takes infinite time. Is there a way to apply the function to each element of the matrix without a loop?