comparison toolboxes/FullBNT-1.0.7/KPMtools/polygon_centroid.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:e9a9cd732c1e
1 function [x0,y0] = centroid(x,y)
2 % CENTROID Center of mass of a polygon.
3 % [X0,Y0] = CENTROID(X,Y) Calculates centroid
4 % (center of mass) of planar polygon with vertices
5 % coordinates X, Y.
6 % Z0 = CENTROID(X+i*Y) returns Z0=X0+i*Y0 the same
7 % as CENTROID(X,Y).
8
9 % Copyright (c) 1995 by Kirill K. Pankratov,
10 % kirill@plume.mit.edu.
11 % 06/01/95, 06/07/95
12
13 % Algorithm:
14 % X0 = Int{x*ds}/Int{ds}, where ds - area element
15 % so that Int{ds} is total area of a polygon.
16 % Using Green's theorem the area integral can be
17 % reduced to a contour integral:
18 % Int{x*ds} = -Int{x^2*dy}, Int{ds} = Int{x*dy} along
19 % the perimeter of a polygon.
20 % For a polygon as a sequence of line segments
21 % this can be reduced exactly to a sum:
22 % Int{x^2*dy} = Sum{ (x_{i}^2+x_{i+1}^2+x_{i}*x_{i+1})*
23 % (y_{i+1}-y_{i})}/3;
24 % Int{x*dy} = Sum{(x_{i}+x_{i+1})(y_{i+1}-y_{i})}/2.
25 % Similarly
26 % Y0 = Int{y*ds}/Int{ds}, where
27 % Int{y*ds} = Int{y^2*dx} =
28 % = Sum{ (y_{i}^2+y_{i+1}^2+y_{i}*y_{i+1})*
29 % (x_{i+1}-x_{i})}/3.
30
31 % Handle input ......................
32 if nargin==0, help centroid, return, end
33 if nargin==1
34 sz = size(x);
35 if sz(1)==2 % Matrix 2 by n
36 y = x(2,:); x = x(1,:);
37 elseif sz(2)==2 % Matrix n by 2
38 y = x(:,2); x = x(:,1);
39 else
40 y = imag(x);
41 x = real(x);
42 end
43 end
44
45 % Make a polygon closed ..............
46 x = [x(:); x(1)];
47 y = [y(:); y(1)];
48
49 % Check length .......................
50 l = length(x);
51 if length(y)~=l
52 error(' Vectors x and y must have the same length')
53 end
54
55 % X-mean: Int{x^2*dy} ................
56 del = y(2:l)-y(1:l-1);
57 v = x(1:l-1).^2+x(2:l).^2+x(1:l-1).*x(2:l);
58 x0 = v'*del;
59
60 % Y-mean: Int{y^2*dx} ................
61 del = x(2:l)-x(1:l-1);
62 v = y(1:l-1).^2+y(2:l).^2+y(1:l-1).*y(2:l);
63 y0 = v'*del;
64
65 % Calculate area: Int{y*dx} ..........
66 a = (y(1:l-1)+y(2:l))'*del;
67 tol= 2*eps;
68 if abs(a)<tol
69 disp(' Warning: area of polygon is close to 0')
70 a = a+sign(a)*tol+(~a)*tol;
71 end
72 % Multiplier
73 a = 1/3/a;
74
75 % Divide by area .....................
76 x0 = -x0*a;
77 y0 = y0*a;
78
79 if nargout < 2, x0 = x0+i*y0; end