Writing a code to find area of polygon
27 次查看(过去 30 天)
显示 更早的评论
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!!!!
0 个评论
回答(4 个)
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
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
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
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
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)])))
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Elementary Polygons 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!