function c = polyCentroid( v )
%c = polyCentroid( v )
%   Compute the centroid of the polygon whose vertexes are the rows of v.
%   The polygon must be 2 or 3 dimensional.
    
    twoD = size(v,2)==2;
    if twoD
        v = [ v zeros( size(v,1), 1 ) ];
    end

    % Find the avergae of the vertexes and move the origin to there.
    p = sum( v, 1 )/size( v, 1 );
    v = v - repmat( p, size(v,1), 1 );
    
    vv = v( [ (2:size(v,1)), 1 ], : );
    tc = (v + vv)/3;  % Locations of centroids of the triangles.
    as = sqrt( sum( cross( v, vv, 2 ).^2, 2 ) );  % Twice the areas of the triangles.
    
    % Sum of centroids, weighted by twice area.
    c = sum( tc .* repmat( as, 1, size( tc, 2 ) ), 1 );
    % Normalise by area and translate to original position.
    c = c/sum(as) + p;
    
    if twoD
        % Cut off the third coordinate.
        c = c([1 2]);
    end
end
