I would like to enumerate the elements of a 2-dimensional NumPy array excluding the first and last row and column (i.e. the ones in the matrix below).
import numpy as np
q = np.zeros((4, 4))
q[1, 1] = 1
q[1, 2] = 1
q[2, 1] = 1
q[2, 2] = 1
# [[0. 0. 0. 0.]
# [0. 1. 1. 0.]
# [0. 1. 1. 0.]
# [0. 0. 0. 0.]]
I can enumerate every element using and add conditionals checking to the first and last row/column but this seems crude:
for ij, q_ij in np.ndenumerate(q):
print(ij, q_ij)
When I slice off the first and last columns and rows i
and j
are off by one
for ij, q_ij in np.ndenumerate(q[1:-1, 1:-1]):
i, j = ij
original_ij = (i + 1, j + 1)
print(original_ij, ij, q_ij)
# (1, 1) (0, 0) 1.0
# (1, 2) (0, 1) 1.0
# (2, 1) (1, 0) 1.0
# (2, 2) (1, 1) 1.0
I can obviously adjust i
and j
to properly refer to the original matrix. For the sale of clarity, I am attempting to calculate the laplacian for a scalar field (e.g. temperature)
laplacian[i][j] = q[i+1][j] + q[i-1][j] + q[i][j+1] + q[i][j-1] - 4*a[i][j]
and need to avoid the boundary elements.
Is there a more elegant way to do this?