How to select in a matrix a given index and its neighbors using numpy in python ?


Example of how to select in a matrix a given index and its neighbors using numpy in python:

Create a matrix with numpy

Let's create a matrix of dimension (6,6):

import numpy as np

A = np.arange(36)
A = A.reshape(6,6)

print(A)

returns

[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]
 [24 25 26 27 28 29]
 [30 31 32 33 34 35]]

Select in a matrix a given index and its neighbors

Let's select for example the index (3,4):

index = [3,4]

the value associated with the above index is:

print(A[3,4])

22

To select first neighbors from this index, a solution is to do:

num_neighbor = 1

left = max(0,index[0]-num_neighbor)
right = max(0,index[0]+num_neighbor+1)

bottom = max(0,index[1]-num_neighbor)
top = max(0,index[1]+num_neighbor+1)

sample = A[left:right,bottom:top]

    print(sample)

returns

[[15 16 17]
 [21 22 23]
 [27 28 29]]

References