Writing a code to find area of polygon

조회 수: 17 (최근 30일)
Sutton Yanosky
Sutton Yanosky 2013년 12월 3일
답변: Steven Lord 2023년 2월 11일
How do I write a code that will calculate the area of a polygon, by using coordinates of the corners of the polygon. I am not sure how to do this. Hint is I will have to use the cosine law????? Please help!!!!

답변 (4개)

Sean de Wolski
Sean de Wolski 2013년 12월 3일
pa = @polyarea
area = pa(x,y)
Where x and y are your coordinates

sixwwwwww
sixwwwwww 2013년 12월 3일
If you have coordinates of the corners in the form of (x1, y1) and (x2, y2) format and also if you like to calculate the area of polygon for variable number of sied then you can do it as follows:
% coordinates of first point
x1 = 1;
y1 = 2;
% coordinates of second point
x2 = 5;
y2 = 6;
% length of a side of polygon
s = sqrt((y2 - y1)^2 + (x2 - x1)^2);
% number of sides in polygon
N = 6;
% Area of polygon
A = (s^2 * N) / (4 * tand(180 / N));
% display area in command window
fprintf('Area of polygon is: %.2f\n', A)
I hope it helps. Good luck!
  댓글 수: 1
Roger Stafford
Roger Stafford 2013년 12월 4일
That method would only be valid for a polygon with all sides and all inner angles equal. However, Sutton did not state that the polygon is regular in this way.

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


Roger Stafford
Roger Stafford 2013년 12월 4일
If you wish to avoid using 'polyarea', one method is this. Let x and y be vectors of the corresponding coordinates of the polygon's vertices taken in counterclockwise order around the polygon.
area = 1/2*sum(x.*y([2:end,1])-y.*x([2:end,1]));
  댓글 수: 2
Dan Kristen
Dan Kristen 2022년 10월 5일
Hi Roger, it'd be nice to have an explanation, since I am new in Matlab. There's negative answer, and I had to make area_new = abs(area) to make it positive. How to make it in clockwise order? Is there any other way of not using the .* notation?
Kurt
Kurt 2023년 2월 11일
Wikipedia has very nice explanation of the Shoelace formula
For a counter clockwise version w/o the element by element operator (.), use dot
1/2*abs(dot(x,[y(2:end) y(1)]) - dot(y,[x(2:end) x(1)]))
For a clockwise version, reverse each array
1/2*abs(dot(x(end:-1:1),[y(1) y(end:-1:2)]) - dot(y(end:-1:1),[x(1) x(end:-1:2)]))
Another clockwise version, same as above, but uses fliplr to reverse each array
1/2*abs(dot(fliplr(x),fliplr([y(2:end) y(1)])) - dot(fliplr(y),fliplr([x(2:end) x(1)])))

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


Steven Lord
Steven Lord 2023년 2월 11일
This wasn't an option when the original question was asked but you could create a polyshape then call area on it. In this example p is a square with sides of length 2 (as you can see from the plot) which means it has an area of 4.
p = nsidedpoly(4, SideLength=2);
A = area(p)
A = 4
plot(p)

카테고리

Help CenterFile Exchange에서 Computational Geometry에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by