MATLAB: How to find all neighbours of an element in N-dimensional matrix

neighboursspatial searchStatistics and Machine Learning Toolbox

I just can't wrap my head around how to find all neighbours of an element in a N-dimensional matrix. After reading through the documentation on spatial searching I think it could be done using the Delaunay triangulation. However, these topics are still a bit too advanced for me, so any help would be appreciated.

Best Answer

What I often like to do is make an offset mask, as follows
s=size(yourmatrix);
N=length(s);
[c1{1:N}]=ndgrid(1:3);
c2(1:N)={2};
offsets=sub2ind(s,c1{:}) - sub2ind(s,c2{:})
Now, for any linear index in your matrix L, you can get all its neighbors by doing
neighbors = yourmatrix(L+offsets)
It won't work at the edges of the matrix, but you can take care of that by padding the edges first.