How to find neighbor matrix?

1 view (last 30 days)
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
  1 Comment
Walter Roberson
Walter Roberson on 3 Dec 2015
table((i-1),(j+1)) attempts to index table(0,2) because i starts at 1.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 3 Dec 2015
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
  2 Comments
Tan Wen Kun
Tan Wen Kun on 7 Dec 2015
Edited: Tan Wen Kun on 7 Dec 2015
Your solution just extracted 1 from the labelimg, that not I want.
What I want is when is label= 1 2 1 3 1
I made table(2,3)=1 and table(3,2)=1
Attempted to access labelimg(214,0); index must be a positive integer or logical.
for i=1:max(labelimg(:))
for j=1:max(labelimg(:))
if labelimg(i,j)==1 %1 is the border
if labelimg(i,j-1) ~=1
if labelimg(i,j+1) ~=1
table(j-1,j+1) =1 ;
table(j+1,j-1) =1 ;
how to solve this when I using j-1 when loop first element got problem and also j+1 when loop last element?How to solve the index out of bound?
Walter Roberson
Walter Roberson on 7 Dec 2015
maxlab = max(labelimg(:));
for i = 1 : maxlab
for j = 2 : maxlab - 1
Now you can test labelimg(i,j-1) and labelimg(i,j+1)

Sign in to comment.

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!