How to calculate average of closest neighbours in an array in numpy
Scipy has a scipy.ndimage.convolve function, which can do exactly this. it takes the array, and a matrix of values to multiply the neighbors with. It should work for any number of dimensions.
However if you are trying to write this function manually, I'd suggest trying an iterative or recursive approach, where each iteration or layer of recursion handles a dimension. In a 3D case, you would first handle the first dimension, and have the one sixth of the value of the neighbors in that dimension. The next iteration would do the same for dimension 2, etc.
The factor to multiply each neighbor with is 1/(2n), since each entry has 2 neighbors in each dimension. This should scale up to any arbitrary number of dimensions.
Given an arbitrary array with real numbers as entries, I want to return an array with the same shape, whose entries are the average over the closest neighbours of the original array.
What I mean by this in the case of a given array of dimension 2, is that if the array has shape (n,m) with entries a_{i,j}, then on the entry (i,j) the value of the new array should be:
average(i,j)=1/4 (a_{i+1,j} + a_{i-1,j} + a_{i,j+1} + a_{i,j-1}),
where the first index is taken mod n and the second mod m.
I would like to create a function whose argument is an arbitrary array, and returns an array of the same shape and entries the averages over the entries on the closest neighbours of the given array (for a d-dimensional array there are 2d closest neighbours, obtained by summing +1 and -1 on each index)
I know how to do this for a fixed dimension d (just generalising the above equation), using d nested for loops, but I don't know how to do it when the dimensions are not fixed.