Writing a code to find area of polygon

24 views (last 30 days)
Sutton Yanosky
Sutton Yanosky on 3 Dec 2013
Answered: Steven Lord on 11 Feb 2023
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!!!!

Answers (4)

Sean de Wolski
Sean de Wolski on 3 Dec 2013
pa = @polyarea
area = pa(x,y)
Where x and y are your coordinates

sixwwwwww
sixwwwwww on 3 Dec 2013
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 Comment
Roger Stafford
Roger Stafford on 4 Dec 2013
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.

Sign in to comment.


Roger Stafford
Roger Stafford on 4 Dec 2013
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 Comments
Dan Kristen
Dan Kristen on 5 Oct 2022
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 on 11 Feb 2023
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)])))

Sign in to comment.


Steven Lord
Steven Lord on 11 Feb 2023
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)

Categories

Find more on Elementary Polygons in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!