MATLAB: Finding neighbor of a position

neighbor

Hi, I have a matrix.
I =
1 0 0
2 5 0
0 0 3
0 0 0
I know the position of 5 in I is 6 linear index.
is there any easy function to have the 8 other neighbors of 5. Thanks

Best Answer

EDITED: should be fine now
I =[ 1 0 0
2 5 0
0 0 3
0 0 0];
l = 8;
sz = size(I);
% row, col subs of center
[r,c] = ind2sub(sz,l); % c = ceil(l/4); r = mod(l,4)+ c*sz(1);
% Calculate 8 neighbors
neigh(1:8,1:2) = [r+[-1;0;1;-1;1;-1;0;1] c+[-1;-1;-1;0;0;1;1;1] ];
% Only those in the range
neigh = neigh(all(neigh,2) & neigh(:,1) <= sz(1) & neigh(:,2) <= sz(2),:);
% Convert to position
idx = (neigh(:,2)-1)*sz(1) + neigh(:,1);