Search code examples
matlabfunctiondefined

MATLAB function for calculating the area of polygon using sum of triangle areas


I have a question regarding a MATLAB function I have written. It takes as input a set of x and y vertex coordinates in the form of two row vectors, and uses these to calculate the area of a polygon.

For the single triangle case it runs fine (although I KNOW my code could be made more efficient and to look better). However, I am to use this function in a script that takes a set of x and y points and calculates the perimeter and area of the polygon bounded by the coordinate points.

Using the function I created for the area of a triangle, the area of the polygon can be calculated based on these steps:

  • there are N - 2 triangles (where N is the amount of sides to the polygon)
  • my function calculates the area of these triangles
    (using A = 0.5(x1*(y2-y3)-x2*(y1-y3)+x3(y1-y2))
  • sum the triangular areas to find the area of the polygon.

I have my code written below. My perimeter function works very well, but I am not sure how to implement the area function for the triangle into the polygon area program. I believe that my formula is correct, and the problem lies somewhere in the loop indexing.

Any suggestions on how to proceed from what I have below would be appreciated!

function [tri_area] = area2dd(coords_x,coords_y)

%%Input argument check
narginchk(2,2) ;

%%Calculation
% % ii = 1:length(coords_x)-2;
% % jj = 1:length(coords_y)-2;

if length(coords_x) == 3 
    ii = 1:length(coords_x) -2;
    jj = 1:length(coords_y) -2;
    tri_area = sum(abs(0.5.*(coords_x(ii).*(coords_y(jj+1)-21coords_y(jj+2))-coords_x(ii+1)... 
        .*(coords_y(jj)-coords_y(jj+2))+coords_x(ii+2).*(coords_y(jj)-23coords_y(jj+1)))))
else
    ii = 1:3:length(coords_x) -2;
    jj = 1:3:length(coords_y) -2;
    tri_area = sum(abs(0.5.*(coords_x(ii).*(coords_y(jj+1)-29coords_y(jj+2))-coords_x(ii+1)... 
       .*(coords_y(jj)-coords_y(jj+2))+coords_x(ii+2).*(coords_y(jj)-31coords_y(jj+1)))))
end

Solution

  • Ok, so for any interested parties or anyone else who might be solving a problem like mine I have the final WORKING code written below. This function can do double duty. If the coordinate vectors input are in 3 pairs then the function will calculate the area of a triangle. If there are more than 3 sets of coordinate pairs then it will calculate the area of the polygon bounded by those coordinates.

    narginchk(2,2) ;
    if length(coords_x) == 3 
    ii = 1
    jj = 1
    area = sum(abs(0.5.*(coords_x(ii).*(coords_y(jj+1)-coords_y(jj+2))- ...
    coords_x(ii+1).*(coords_y(jj)-coords_y(jj+2))+coords_x(ii+2).*...       
    (coords_y(jj)-coords_y(jj+1))))) ;
    else
    ii = 1:length(coords_x) -3 ;
    jj = 1:length(coords_y) -3 ;
    area = sum((abs(0.5.*(coords_x(1).*(coords_y(jj+1)-coords_y(jj+2)) ...
    -coords_x(ii+1)... 
    .*(coords_y(1)-coords_y(jj+2))+coords_x(ii+2).*(coords_y(1)- ...
    coords_y(jj+1)))))) ;
    end
    end