What's wrong with my polygon area calculator code

조회 수: 1 (최근 30일)
Mert Ayduman
Mert Ayduman 2016년 10월 26일
답변: John D'Errico 2016년 10월 26일
Hi, I wrote this code. It essentially calculates area of a polygon when given coordinates by shoelace formula. But it gives me wrong answer. Couldn't figure out why.
function AreaOfPolygon = gaussarea (xymatrice)
[r,c]=size(xymatrice);
x=xymatrice(:,1);
y=xymatrice(:,2);
calculation=0;
x1=xymatrice(1,1);
y1=xymatrice(1,2);
xLast=xymatrice(r,1);
yLast=xymatrice(r,2);
for i=1:r
if i==1
calculation=calculation+(x1*(y(i+1)-yLast));
elseif i==r
calculation=calculation+(xLast*(y1-y(i-1)));
else
calculation=calculation+(x(i)*y(i+1)-y(i-1));
end
end
AreaOfPolygon=abs(calculation)/2
end
  댓글 수: 1
John D'Errico
John D'Errico 2016년 10월 26일
I suppose there is a good reason why you do not just use polyarea?

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

채택된 답변

John D'Errico
John D'Errico 2016년 10월 26일
It seems to work for me. A simple case:
x = [0 0 1 1 0];
y = [0 1 1 0 0];
xymatrice = [x',y'];
AreaOfPolygon
AreaOfPolygon =
1
polyarea(x,y)
ans =
1
When I ran your code, it yields 1 as the result, which is indeed the area of that square.
So perhaps you can show an example where you think there is a problem. It may be a case where you have a complex polygon that is self intersecting. In that case
xymatrice = rand(10,2);
AreaOfPolygon =
1.0281
polyarea(xymatrice(:,1),xymatrice(:,2))
ans =
0.060961
So in this rather nasty case the two give different results.
plot(x,y,'o-')
But in that case, the "area" is a complicated thing.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by