As long as you know the dimensions of your 3D array, you can compute the linear offsets of all the elements of the 3x3x3 neighborhood. To illustrate this, consider a 2D example of a 4x5 matrix. The linear indices look like this:
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
The 3x3 neighborhood of 10 is [5 6 7 9 10 11 13 14 15]
. The 3x3 neighborhood of 15 is [10 11 12 14 15 16 18 19 20]
. If we subtract off the index of the central element, in both cases we get [-5 -4 -3 -1 0 1 3 4 5]
. More generally, for M
xN
matrix we will have [-M-1 -M -M+1 -1 0 1 M-1 M M+1]
, or [(-M+[-1 0 1]) -1 0 1 (M+[-1 0 1])]
.
Generalizing to three dimensions, if the array is M
xN
xP
, the linear index offsets from the central element will be [(-M*N+[-M-1 -M -M+1 -1 0 1 M-1 M M+1]) [-M-1 -M -M+1 -1 0 1 M-1 M M+1] (M*N+[-M-1 -M -M+1 -1 0 1 M-1 M M+1])]
. You can reshape this to 3x3x3 if you wish.
Note that this sort of indexing doesn't deal well with edges; if you want to find the neighbors of an element on the edge of the array you should probably pad the array on all sides first (thereby changing M
, N
, and P
).