MATLAB: How to find neighbor matrix

matrix

This is some code i write:
for i=1:h %h=height of the image

for j=1:w %w=width of image

if (i,j)==1 %1 is the border

if (i,j-1) ~=1 && if(i,j+1) ~=1
table(j-1,j+1) =1
table(j+1,j-1) =1
for j=1:w %w=width of image
for i=1:h %h=height of the image
if (j,1)==1 %1 is the border
if (j,i-1) ~=1 && if(j,i+1) ~=1
table(i-1,i+1) =1
table(i+1,i-1) =1
I hope loop horizontal and vertical to find the neighbor matrix dont care of diagonal situation.
As long as it read x then read 1 then read y then (x,y) and(y,x)=1
How to solve this?
A=
1 1 1 1 1 1 1 1 1 1
1 2 2 1 3 3 1 4 4 1
1 2 2 1 3 1 5 5 5 1
1 1 1 1 1 1 1 1 1 1
result=
2 3 4 5
2 1 1 0 0
3 1 1 1 1
4 0 1 1 1
5 0 1 1 1

Best Answer

table = (A == 1);
s = max(size(table,1),size(table,2));
if s ~= size(table,1) || s ~= size(table,2)
table(s,s) = false; %make it square
end
table = table | table.'; %make it symmetric