How to find neighbor matrix?

1 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2015-12-3
table((i-1),(j+1)) attempts to index table(0,2) because i starts at 1.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2015-12-3
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 个评论
Tan Wen Kun
Tan Wen Kun 2015-12-7
编辑:Tan Wen Kun 2015-12-7
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 2015-12-7
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)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by