Computes the centroid of a curve defined by a series of points. PT = polylineCentroid(POINTS); Computes center of mass of a polyline defined by POINTS. POINTS is a N-by-D array of double, representing a set of N points in a D-dimensional space. PT = polylineCentroid(PTX, PTY); PT = polylineCentroid(PTX, PTY, PTZ); Specifies points as separate column vectors PT = polylineCentroid(..., TYPE); Specifies if the last point is connected to the first one. TYPE can be either 'closed' or 'open'. Example poly = [0 0;10 0;10 10;20 10]; polylineCentroid(poly) ans = [10 5] See also: polygons2d, centroid, polygonCentroid, polylineLength
0001 function center = polylineCentroid(varargin) 0002 % Computes the centroid of a curve defined by a series of points. 0003 % 0004 % PT = polylineCentroid(POINTS); 0005 % Computes center of mass of a polyline defined by POINTS. POINTS is a 0006 % N-by-D array of double, representing a set of N points in a 0007 % D-dimensional space. 0008 % 0009 % PT = polylineCentroid(PTX, PTY); 0010 % PT = polylineCentroid(PTX, PTY, PTZ); 0011 % Specifies points as separate column vectors 0012 % 0013 % PT = polylineCentroid(..., TYPE); 0014 % Specifies if the last point is connected to the first one. TYPE can be 0015 % either 'closed' or 'open'. 0016 % 0017 % Example 0018 % poly = [0 0;10 0;10 10;20 10]; 0019 % polylineCentroid(poly) 0020 % ans = 0021 % [10 5] 0022 % 0023 % See also: 0024 % polygons2d, centroid, polygonCentroid, polylineLength 0025 % 0026 0027 % --------- 0028 % author : David Legland 0029 % INRA - TPV URPOI - BIA IMASTE 0030 % created the 22/05/2006. 0031 % 0032 0033 0034 0035 %% process input arguments 0036 0037 % check whether the curve is closed 0038 closed = false; 0039 var = varargin{end}; 0040 if ischar(var) 0041 if strcmpi(var, 'closed') 0042 closed = true; 0043 end 0044 % remove last argument 0045 varargin(end) = []; 0046 end 0047 0048 % extract point coordinates 0049 if length(varargin)==1 0050 points = varargin{1}; 0051 elseif length(varargin)==2 0052 points = [varargin{1} varargin{2}]; 0053 end 0054 0055 0056 %% Main computation 0057 0058 % compute centers and lengths composing the curve 0059 if closed 0060 centers = (points + points([2:end 1],:))/2; 0061 lengths = sqrt(sum(diff(points([1:end 1],:)).^2, 2)); 0062 else 0063 centers = (points(1:end-1,:) + points(2:end,:))/2; 0064 lengths = sqrt(sum(diff(points).^2, 2)); 0065 end 0066 0067 % centroid of edge centers weighted by edge length 0068 %weigths = repmat(lengths/sum(lengths), [1 size(points, 2)]); 0069 center = sum(centers .* repmat(lengths, [1 size(points, 2)]), 1) / sum(lengths); 0070