source("http://macosa.dima.unige.it/r.R") # If I have not already loaded the library
       
S 07 Centroid (and Barycenter)
# With centerPol(x,y) I have the centroid of the polygon "x,y". See above on the left.
BF = 3; HF = 3; x = c(1,4,6,1); y = c(0,1,6,4); PLANE(0,6,0,6)
polyC(x,y,"green"); BOX(); Line(1,4, 4,1,"red"); LIne(1,0, 6,6,"blue"); centerPol(x,y)
# 3.060606 2.939394
POINT(centerPol(x,y)[1],centerPol(x,y)[2],"brown")
# Line and LIne (unlike line, which tracks segments as segm but thin) dot the
# segments (with short/long dashes).
# If the polygon were made of a sheet, the centroid would coincide with the barycenter.
# But centroid coordinates are not the average of the coordinates of the vertices. See
# above in the center.
BF = 3; HF = 3; x = c(1,4,6,1); y = c(0,1,6,4); PLANE(0,6,0,6)
POINT(x,y,"seagreen"); u=mean(x); v=mean(y); POINT(u,v,"brown"); u;v
# 3 2.75
# In the case of isolated masses m1,m2, … located at the points x1,y1, x2,y2, …, if I
# put m = c(m1,m2,…), x = c(x1,x2,…), y = c(y1,y2,…), the barycenter coordinates are:
# sum(m*x)/sum(m); sum(m*y)/sum(m) But (equivalently) I can compute the weighted mean:
# Wmean(x, m); Wmean(y, m)
# See above on the right, where the blue objects have double mass:
BF = 3; HF = 3; x = c(1,4,6,1); y = c(0,1,6,4); PLANE(0,6,0,6)
POINT(x[1:2],y[1:2],"blue"); Point(x[3:4],y[3:4],"seagreen");
m=c(2,2,1,1); u=Wmean(x,m); v=Wmean(y,m)
POINT(u,v,"brown"); u; v
# 2.833333 2
In the figure on the right, y of centroid is 10; we find x:
15·30·20 = 7*pi*5^2 + x*(30*20pi*5^2)
x = (15*6007*pi*5^2)/(600pi*5^2) = 16.20492 

# The centroid of Italy.
# I can upload coordinates (separated by ",") from an external file.
# For example, if I copy the coordinates that are in the penisola file and then paste
# them, after I have typed:
# I = c( and finally ) in order to get:
# I = c(
# 8,46,
# 7.87,45.9,
# ...
# 8,46
# )
# Here's what I obtain with these other commands:
X = xTab(I); Y = yTab(I)
BF = 4; HF = 4; Plane(min(X),max(X), min(Y),max(Y)); polyline(X,Y, "blue")
C = centerPol(X,Y); C; POINT(C[1],C[2],"red")
# 12.18996 43.48932
Plane(min(X),max(X), min(Y),max(Y)); polyC(X,Y, "green"); polyl(X,Y, "red")
POINT(C[1],C[2],"red") # It is "Cittą di Castello" (see)
# See here for uploading data like those of "penisola" saved as a table (read.table),
# also (using dec=",") if they are written in Italian notation.
# See here to determine the area of the surface of Italy, and to print it with a scale
# showing (approximately) the kilometers:
# See also here.
Other examples of use