# Simple method for getting indices of a sub array along top, bottom or side of larger matrix A?

I am trying to figure out how to get a sub array out of larger Array, A (MxN). The question is not about whether to use slice or view. I do not need to change the original matrix A, so I will be using slice. I need to get a sub array of neighbors at (i,j) Starting at N these would be the indices often labeled: N,NE,E,SE,S,SW,W,NW. I can write a function that uses a series of if’s to handle the boundary conditions(i=0,j=0,i=M,j=N). Is there a more simple, more elegant way of handling the boundaries while returning the (i,j)'s of the neighbors cells, for example, as a vector of tuples, each tuple containing the proper (i,j). For example say A is (5x4) and for cell (1,4) the function returns [(2,4),(2,3),(1,3)]. These are the indices of the surrounding element (1,4) going clockwise. Any suggestions?

My take:

``````neighbors(n, m, i, j) =
((i + di, j + dj)
for (di, dj) in ((-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1))
if 1 <= i + di <= n && 1 <= j + dj <= m)

collect(neighbors(5, 4, 1, 4))
``````

Thank you