Ekat Sim
Ekat Sim

Reputation: 125

get neighbors of a max value in 2D numpy array

I have a 2D array of shape 10x10 and I need to find the neighbors of a maximum value in a 2D array. My code is:

import numpy as np
array = np.random.randint(-10,10, size=(10,10))

max_index = np.argmax(array)

def get_coordinate_i(value):
        i = 0
        if value % 10 >= 1:
            i = value // 10
        return i

j = max_index - 10*get_coordinate_i(max_index)
i = get_coordinate_i(max_index)

def fun(i, j, array):
    arr = np.array([])
    if i!=0 and j!=0 and i!=9 and j!=9:
        for val in range(-1,2):
            for val2 in range(-1,2):
                arr = np.append(arr, array[i+val][i+val2])
    return np.reshape(arr, (3,3))

Though, it is not working properly every time.

Upvotes: 1

Views: 608

Answers (2)

FBruzzesi
FBruzzesi

Reputation: 6475

Avoiding loops:

a = np.random.randint(0,100, (10,10))
x, y = np.unravel_index(a.argmax(), a.shape)

box = a[np.max([x-1, 0]):np.min([x+1, 9])+1, np.max([y-1, 0]):np.min([y+1, 9])+1]

Remark that this does not account for multiple occurrence of the max value, and argmax() method stops at first occurance.

Upvotes: 1

Rohit Sohlot
Rohit Sohlot

Reputation: 29

you can calculate the i,j and the matrix around the max. value in a different sorter way.

import numpy as np
array = np.random.randint(-10,10, size=(10,10))
max_index = np.argmax(array)
j = max_index%10
i = max_index//10

if j==0:
    matrix_around_max =array[i-1:i+2,j:j+2]
elif i ==0:
    matrix_around_max = array[i:i+2,j-1:j+2]
elif i==0 and j==0:
    matrix_around_max = array[i:i+2,j:j+2]
else:
    matrix_around_max = array[i-1:i+2,j-1:j+2]

Upvotes: 0

Related Questions