Fastest calculation method to: Count elements in a matrix, in the neighborhood of some element, having some value

1 次查看(过去 30 天)
For an element (i,j) in a matrix I want to calculate the number of neighboring elements which have the same value as that in (i,j). I currently have made the straightforward code:
for i=2:ynum+brd2-1
for j=2:xnum+brd2-1
if x(i,j)==x(i-1,j+1)
e(i,j)=e(i,j)+1;
end;
if x(i,j)==x(i,j+1)
e(i,j)=e(i,j)+1;
end;
if x(i,j)==x(i+1,j+1)
e(i,j)=e(i,j)+1;
end;
if x(i,j)==x(i-1,j)
e(i,j)=e(i,j)+1;
end;
if x(i,j)==x(i+1,j)
e(i,j)=e(i,j)+1;
end;
if x(i,j)==x(i-1,j-1)
e(i,j)=e(i,j)+1;
end;
if x(i,j)==x(i,j-1)
e(i,j)=e(i,j)+1;
end;
if x(i,j)==x(i+1,j-1)
e(i,j)=e(i,j)+1;
end;
e(i,j)=8-e(i,j);
end
end
which works just fine and is designed for a 9 point stencil (I look at the 8 nearest neighbors).
The problem is that it is slow (or probably much slower than another method) and I want to do the same thing with a 37 point stencil that looks like this:
000
00000
0000000
000X000
0000000
00000
000
where the x is (i,j), instead of
000
0X0
000
I assume I should use some kind of countif or sum(sum())methods, but I am new to matlab and do not know what the fastest operations are.
Is it fastest to count over a rectangle around the circle and then subtract the 3 points near the vertices?
Thanks
  2 个评论
Matt J
Matt J 2013-11-24
编辑:Matt J 2013-11-24
Are there any special restrictions that on the matrix data that you're working with? I would guess, for example, that the x(i,j) values are all integers. Otherwise, you would be comparing x(i,j) with its neighbors using a tolerance for floating point differences.

请先登录,再进行评论。

回答(1 个)

Matt J
Matt J 2013-11-24
编辑:Matt J 2013-11-24
I would expect this to be faster. It's for a 3x3 stencil, but it can easily be generalized.
stencil=zeros(3);
stencil(5)=1;
e=zeros(size(x));
for i=[1:4,6:8]
stencil(i)=-1;
e(2:end-1,2:end-1)=e(2:end-1,2:end-1) + ~conv2(x,stencil,'valid');
stencil(i)=0;
end

类别

Help CenterFile Exchange 中查找有关 Spatial Search 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by