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

조회 수: 5 (최근 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.
Image Analyst
Image Analyst 2013년 11월 24일
I guess I'm not understanding why you don' just use the other method which you say is faster. Care to explain?

댓글을 달려면 로그인하십시오.

답변 (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에서 Mathematics and Optimization에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by