I've been working on a code (Py 2.7) that generates an array of elements with each node assigned some random numbers. Now, I wish to make a list of the surrounding elements, and find the index of the max value. The array size is variable (I considered col = array column size). I have assigned numbers to each node (I called it 's' in the below) so that I can find the 2D index of the array element. Here is what I 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)
a = [i for i,j in enumerate(b) if j == ma]
Is there any short method to find the neighbours without the need to number each array element ? (like I did using s).
You can use
numpyfor this. First, let's create a random 5x5 matrixMfor testing...Now we take a slice from this matrix,
N, holding the neighbors of some central element(x, y)We can now get a new matrix showing which of the elements of the orginal matrix
Mis equal to themaxfromNNow we can use
numpy.whereto get the index of the element(s) that areTruein this matrix.zipthose to get a list of tuples.Note that those are the positions in the original matrix
M, i.e. they could contain tuples that are not inN. Alternatively, you can get just the maximum values inN, but then you'll have to addx-1andy-1as offset afterwards.