Home > matGeom > polygons2d > polygonCentroid.m

polygonCentroid

PURPOSE ^

Computes the centroid (center of mass) of a polygon.

SYNOPSIS ^

function [centroid, area] = polygonCentroid(varargin)

DESCRIPTION ^

 Computes the centroid (center of mass) of a polygon.

   CENTROID = polygonCentroid(POLY)
   CENTROID = polygonCentroid(PTX, PTY)
   Computes center of mass of a polygon defined by POLY. POLY is a N-by-2
   array of double containing coordinates of vertices.

   [CENTROID, AREA] = polygonCentroid(POLY)
   Also returns the (signed) area of the polygon. 

   Example
     % Draws the centroid of a paper hen
     x = [0 10 20  0 -10 -20 -10 -10  0];
     y = [0  0 10 10  20  10  10  0 -10];
     poly = [x' y'];
     centro = polygonCentroid(poly);
     drawPolygon(poly);
     hold on; axis equal;
     drawPoint(centro, 'bo');
 
   References
     algo adapted from P. Bourke web page.

   See also:
     polygons2d, polygonArea, polygonSecondAreaMoments, drawPolygon
     polylineCentroid, centroid

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function [centroid, area] = polygonCentroid(varargin)
0002 % Computes the centroid (center of mass) of a polygon.
0003 %
0004 %   CENTROID = polygonCentroid(POLY)
0005 %   CENTROID = polygonCentroid(PTX, PTY)
0006 %   Computes center of mass of a polygon defined by POLY. POLY is a N-by-2
0007 %   array of double containing coordinates of vertices.
0008 %
0009 %   [CENTROID, AREA] = polygonCentroid(POLY)
0010 %   Also returns the (signed) area of the polygon.
0011 %
0012 %   Example
0013 %     % Draws the centroid of a paper hen
0014 %     x = [0 10 20  0 -10 -20 -10 -10  0];
0015 %     y = [0  0 10 10  20  10  10  0 -10];
0016 %     poly = [x' y'];
0017 %     centro = polygonCentroid(poly);
0018 %     drawPolygon(poly);
0019 %     hold on; axis equal;
0020 %     drawPoint(centro, 'bo');
0021 %
0022 %   References
0023 %     algo adapted from P. Bourke web page.
0024 %
0025 %   See also:
0026 %     polygons2d, polygonArea, polygonSecondAreaMoments, drawPolygon
0027 %     polylineCentroid, centroid
0028 
0029 % ------
0030 % Author: David Legland
0031 % e-mail: david.legland@inrae.fr
0032 % Created: 2004-05-05
0033 
0034 % Algorithme P. Bourke, vectorized version
0035 
0036 % HISTORY
0037 % 2012.02.24 vectorize code
0038 
0039 
0040 % parse input arguments
0041 if nargin == 1
0042     var = varargin{1};
0043     px = var(:,1);
0044     py = var(:,2);
0045 elseif nargin == 2
0046     px = varargin{1};
0047     py = varargin{2};
0048 end
0049 
0050 % vertex indices
0051 N = length(px);
0052 iNext = [2:N 1];
0053 
0054 % compute cross products
0055 common = px .* py(iNext) - px(iNext) .* py;
0056 sx = sum((px + px(iNext)) .* common);
0057 sy = sum((py + py(iNext)) .* common);
0058 
0059 % area and centroid
0060 area = sum(common) / 2;
0061 centroid = [sx sy] / 6 / area;

Generated on Wed 16-Feb-2022 15:10:47 by m2html © 2003-2019