Best way to shift a window around a multidimensional Array?

Okay so let’s say I have a multidimensional Array m and I want to extract a window around a center point that has a size of 3 (for example) in every dimension.

The following code does what I want:

m = rand(5,5,5)

center = [2,3,4]

window = m[[ center[i]-1:center[i]+1 for i in 1:ndims(m)]...]

So far so good.
Now, I want to do this for different center points - at every time step of a huge simulation - and for this application my code looks a bit unefficient to me. It seems to me that there should be a way to create the window once and then shift it around different centerpoints - maybe with a @views? I just have not found a way to do it yet.

Does anyone have an idea how to do this more efficiently?

edit: I just discovered that my code does not work when choosing a center close to an edge. I forgot to mention that it should wrap around on the edges.

It depends what you want to do, but I found the following explanations quite useful when writing multidimensional codes


This is essentially the same as the problem discussed here: Matrix Free Differentiation - #3 by stevengj