Python find list of surrounding neighbours of a node in 2D array -


i've been working on code (py 2.7) generates array of elements each node assigned random numbers. now, wish make list of surrounding elements, , find index of max value. array size variable (i considered col = array column size). have assigned numbers each node (i called 's' in below) can find 2d index of array element. here wrote

rn = s/col; cn = s%col; b = [rr[rn,cn+1],rr[rn-1,cn+1],rr[rn-1,cn],rr[rn-1,cn-1],rr[rn,cn-1],rr[rn+1,cn-1],rr[rn+1,cn],rr[rn+1,cn+1]] ma = max(b) = [i i,j in enumerate(b) if j == ma] 

is there short method find neighbours without need number each array element ? (like did using s).

you can use numpy this. first, let's create random 5x5 matrix m testing...

>>> m = np.random.random((5, 5)) >>> m array([[ 0.79463434,  0.60469124,  0.85488643,  0.69161242,  0.25254776],        [ 0.07024954,  0.84918038,  0.01713536,  0.42620873,  0.97347887],        [ 0.3374191 ,  0.99535699,  0.79378892,  0.0504229 ,  0.05136649],        [ 0.73609556,  0.94250215,  0.67322277,  0.49043047,  0.60657825],        [ 0.71153444,  0.43242926,  0.29726895,  0.2173065 ,  0.38457722]]) 

now take slice matrix, n, holding neighbors of central element (x, y)

>>> x, y = 2, 2 >>> n = m[x-1:x+2, y-1:y+2] >>> n array([[ 0.84918038,  0.01713536,  0.42620873],        [ 0.99535699,  0.79378892,  0.0504229 ],        [ 0.94250215,  0.67322277,  0.49043047]]) 

we can new matrix showing of elements of orginal matrix m equal max n

>>> m == n.max() array([[false, false, false, false, false],        [false, false, false, false, false],        [false,  true, false, false, false],        [false, false, false, false, false],        [false, false, false, false, false]], dtype=bool) 

now can use numpy.where index of element(s) true in matrix. zip list of tuples.

>>> zip(*np.where(m == n.max())) [(2, 1)] 

note positions in original matrix m, i.e. contain tuples not in n. alternatively, can maximum values in n, you'll have add x-1 , y-1 offset afterwards.

>>> zip(*np.where(n == n.max())) [(1, 0)] 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -