Writing a code to find area of polygon

15 visualizzazioni (ultimi 30 giorni)
Sutton Yanosky
Sutton Yanosky il 3 Dic 2013
Risposto: Steven Lord il 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!!!!

Risposte (4)

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

sixwwwwww il 3 Dic 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 Commento
Roger Stafford
Roger Stafford il 4 Dic 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.

Accedi per commentare.

Roger Stafford
Roger Stafford il 4 Dic 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 Commenti
Kurt il 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)])))

Accedi per commentare.

Steven Lord
Steven Lord il 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


Scopri di più su Elementary Polygons in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by