Fastest calculation method to: Count elements in a matrix, in the neighborhood of some element, having some value
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Matt J
am 24 Nov. 2013
Bearbeitet: Matt J
am 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
am 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?
Antworten (1)
Matt J
am 24 Nov. 2013
Bearbeitet: Matt J
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Spatial Search finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!