Fastest calculation method to: Count elements in a matrix, in the neighborhood of some element, having some value
1 view (last 30 days)
Show older comments
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 Comments
Matt J
on 24 Nov 2013
Edited: Matt J
on 24 Nov 2013
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
on 24 Nov 2013
I guess I'm not understanding why you don' just use the other method which you say is faster. Care to explain?
Answers (1)
Matt J
on 24 Nov 2013
Edited: Matt J
on 24 Nov 2013
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
0 Comments
See Also
Categories
Find more on Spatial Search in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!