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

    p = sum( v, 1 )/size( v, 1 );
    c = zeros(1,size(v,2));
    for i=1:size(v,1)
        v(i,:) = v(i,:) - p;
    end
    vv = v( [ (2:size(v,1)), 1 ], : );
    aa = 0;
    for i=1:size(v,1)
        tc = (v(i,:) + vv(i,:))*(2/3);
        a = norm(cross( v(i,:), vv(i,:) ));
        c = c + tc * a;
        aa = aa + a;
    end
    c = c/aa + p;
    if twoD
        c = c([1 2]);
    end
end
