Assume I have a $m\times n$ matrix and I would like to extract four neighbors of randomly selected entry of a matrix. I have handled if location is not on the boundary. Any suggestion how to handle it if entry is on the boundary or handle it all in once? Thanks.
Here is an example.
SeedRandom[123];
{n, m} = {4, 6};
mat = RandomInteger[{1, 5}, {n, m}];
MatrixForm@mat
$\text{mat}= \left( \begin{array}{cccccc} 4 & 2 & 3 & 1 & 1 & 3 \\ 4 & 2 & 2 & 5 & 1 & 2 \\ 5 & 4 & 3 & 3 & 5 & 5 \\ 3 & 5 & 2 & 2 & 5 & 3 \\ \end{array} \right)$
loc = {RandomInteger[{2, n - 1}], RandomInteger[{2, m - 1}]}
fourNeighbor = (Extract[mat, # + loc] &) /@ {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}
Edit:
Here is Moore Neighbors
nf = Nearest[Tuples@Range@Dimensions@mat -> Flatten[mat],
DistanceFunction -> ChessboardDistance];
neighbors[pt_] := nf[pt, {All, 1}][[1 ;;]]
Or
mooreNeighborPositions = AdjacencyList[NearestNeighborGraph[Tuples@Range@Dimensions@#,
DistanceFunction -> ChessboardDistance], #2] &;
mooreNeighbors = Extract[#, mooreNeighborPositions@##] &; mooreNeighbors[mat, {1, 1}]