MATLAB: I’m trying to find the area and the center of a polygon

data analysispolygon

I'm trying to find the area and the center of a polygon, made of a set of coordinates, x & y Here is the code I have so far, the results it's giving me are way off, can anyone see the problem?
%Load the polygon points file
load Drawing1.txt;
x = Drawing1(:,1);
y = Drawing1(:,2);
%Calculate the number of rows
Nrows = numel(textread('Drawing1.txt','%1c%*[^\n]'));
%Set initial values
A = 0;
Cx = 0;
Cy = 0;
for k=0:(Nrows-1);
if k==0
%End point is the same as point 0
i=Nrows;
j=1;
else
%Otherwise use the current point
i=k;
j=k+1;
end
%Calculate centre points of polygons
A=A+(((x(i)*y(j))-(x(j)*y(i)))*cosd((y(i)+y(j))/2));
Cx=Cx+((x(i)+x(j))*((x(i)*y(j))-(x(j)*y(i))));
Cy=Cy+((y(i)+y(j))*((x(i)*y(j))-(x(j)*y(i))));
end
%Apply terms outside summation
A=0.5*A
Cx = (1/(6*A))*Cx
Cy = (1/(6*A))*Cy
Thanks!

Best Answer

No reason to reinvent the wheel:
doc polyarea
And here is a function I wrote for centroid calculation:
function [x_bar, y_bar, As] = xycentroid(x,y)
%Function calculates centroid and area of a list of xy points
%SCd 11/24/2010
%



%
%Input Arguments:
% -x: vector of x coordinates (can be row or column vector)
% -y: vector of y coordinates (can be row or column vector)
%
%Output Arguments:
% -x_bar: x location of centroid
% -y_bar: y location of centroid
% -A: area of polygon
%
%Error checking:
assert(nargin==2,'This function expects 2 and only 2 input arguments');
assert(all(size(x(:))==size(y(:))),'Input arguments: x & y are expected to be the same length');
x = x(:);
y = y(:);
%Engine:
A = x(1:end-1).*y(2:end)-x(2:end).*y(1:end-1);
As = sum(A)/2;
x_bar = (sum((x(2:end)+x(1:end-1)).*A)*1/6)/As;
y_bar = (sum((y(2:end)+y(1:end-1)).*A)*1/6)/As;
end
I guess I didn't know about polyarea when I wrote this !