I have a nested for loop function. For each index i and j of a 2D matrix, it sums all the elements of a 2D slice of a 2D array, as in sum(data[i-1:i+1,j-1+i+1])).
import numpy as np
data=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
# This is to specify at the edge indices that the sum wraps around
pad_factor=1
data_padded = np.pad(data, pad_factor, mode='wrap')
print(data_padded)
output:
[[16 13 14 15 16 13]
[ 4 1 2 3 4 1]
[ 8 5 6 7 8 5]
[12 9 10 11 12 9]
[16 13 14 15 16 13]
[ 4 1 2 3 4 1]]
result=np.zeros((np.shape(data)))
for i in range(0,np.shape(data)[0]):
for j in range(0,np.shape(data)[1]):
result[i,j] = np.sum(data_padded[i-1+pad_factor:i+1+pad_factor+1, j-1+pad_factor:j+1+pad_factor+1])
print(result)
output:
[[69. 66. 75. 72.]
[57. 54. 63. 60.]
[93. 90. 99. 96.]
[81. 78. 87. 84.]]
However, on a larger array this takes far too long. So I'd like to vectorize it. I've tried creating a meshgrid, then inputting these arrays into the formula:
i, j = np.mgrid[0:np.shape(data)[0],0:np.shape(data)[1]]
result=np.sum(data_padded[i-1:i+1+1,j-1:j+1+1])
This produces the error:
TypeError: only integer scalar arrays can be converted to a scalar index
It doesn't like to take a slice of an array given an array as input.
However, the same method works to take a single element in the matrix, for example:
i, j = np.mgrid[0:np.shape(data)[0]-1,0:np.shape(data)[1]-1]
result=data[i,j]
print(result)
output
[[ 1 2 3]
[ 5 6 7]
[ 9 10 11]]
So I'd like to know if there is a way to accomplish this.
I'm also interested in solutions for vectorizing the original problem.