1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.