Writing a code to find area of polygon
17 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (4)
Sean de Wolski
le 3 Déc 2013
pa = @polyarea
area = pa(x,y)
Where x and y are your coordinates
0 commentaires
sixwwwwww
le 3 Déc 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 commentaire
Roger Stafford
le 4 Déc 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.
Roger Stafford
le 4 Déc 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 commentaires
Dan Kristen
le 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
le 11 Fév 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)])))
Voir également
Catégories
En savoir plus sur Computational Geometry dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!