Easiest way to return sum of a matrix's neighbors in numpy
<p>I am trying to make a program that needs a matrix's neighbor(excluding itself) sum ex:</p>

<pre><code> matrix([[0, 0, 0],
        [1, 0, 1],
        [0, 1, 0]])  
</code></pre>

<p>would return:</p>

<pre><code>matrix([[1, 2, 1],
        [1, 3, 1],
        [2, 2, 2]])
</code></pre>

<p>I have a working code here but its big and messy and I'm new to numpy so I need some help cleaning it up and optimizing. (I feel like there has to be a better way)</p>

<p>example code:</p>

<pre><code>import numpy as np

def NiSum(m):
    new = []
    for x in range(m.shape[0]-1):
        row = []
        for y in range(m.shape[1]-1):
            Ni = 0
            for a in [1,1],[1,0],[1,-1],[0,1],[0,-1],[-1,1],[-1,0],[-1,-1]:
                Ni += m[x+a[0],y+a[1]]
            row.append(Ni)
        new.append(row)
    return np.matrix(new)


example = np.matrix('0 0 0 0 0 0 0 0; '*3+'0 0 0 1 1 1 0 0; '*3+'0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 ')

NiSum(example)
</code></pre>

<p>Thanks for any help !</p>

<p>Define a function which computes the sum of all neighbors for a matrix entry, if they exist:</p>

<pre><code>def sumNeighbors(M,x,y):
    l = []
    for i in range(max(0,x-1),x+2): # max(0,x-1), such that no negative values in range() 
        for j in range(max(0,y-1),y+2):
            try:
                t = M[i][j]
                l.append(t)
            except IndexError: # if entry doesn't exist
                pass
    return sum(l)-M[x][y] # exclude the entry itself
</code></pre>

<p>Then you can iterate for every entry in your matrix and pass its result into a new matrix N:</p>

<pre><code>import numpy as np

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

M = np.asarray(M)
N = np.zeros(M.shape)

for i in range(M.shape[0]):
    for j in range(M.shape[1]):
        N[i][j] = sumNeighbors(M, i, j)

print "Original matrix:\n", M
print "Summed neighbors matrix:\n", N
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>Original matrix:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Summed neighbors matrix:
[[ 11.  19.  13.]
 [ 23.  40.  27.]
 [ 17.  31.  19.]]
</code></pre>

python python-3.x numpy matrix scipy