To check that the polygon is regular, you need the distance of all points, including the "last" point of your polygon to the "first" - in the code examples below, if you do not "close" the polygon, you will have an incorrect result in the first case.
And in that case you don’t need the function apply
. dist
already gives you the distance between all points, so what you need is to take the diagonal of the bottom (or top) of the matrix that it returns to you.
And as @Jjoao noted, the condition of equal sides is necessary, but not enough for the polygon to be regular. All their angles need to be identical as well. One way to verify this, given that the sides are equal, is to verify that the center of the polygon is equidistant from all points. The updated code is below.
verifica_lados_iguais <- function(poligono) {
no_vertices <- nrow(poligono)
poligono_fechado <- rbind(poligono, poligono[1])
distancias <- diag(as.matrix(dist(poligono_fechado))[1:no_vertices, 2:(no_vertices + 1)])
lados_iguais <- all(distancias == distancias[1])
}
verifica_equidistancia_centro <- function(poligono) {
c <- apply(poligono, 2, sum) / nrow(poligono)
dist_centro <- apply(poligono, 1, function(p) sqrt((c[1] - p[1])^2 + (c[2] - p[2])^2))
equidistanteCentro <- all((abs(dist_centro - dist_centro[1]) < 0.00001))
}
verifica_regular <- function(poligono) {
regular <- verifica_lados_iguais(poligono) &&
verifica_equidistancia_centro(poligono)
}
print(quadrilatero <- matrix(c(0, 0, 0, 5, 5, 5, 2, 1), ncol = 2, byrow = TRUE))
print(verifica_regular(quadrilatero))
print(quadrado <- matrix(c(0, 0, 0, 5, 5, 5, 5, 0), ncol = 2, byrow = TRUE))
print(verifica_regular(quadrado))
print(losango <- matrix(c(0, 0, 2, 1, 4, 0, 2, -1), ncol = 2, byrow = TRUE))
print(verifica_regular(losango))
How do you define the polygon? Two-column matrix (X, Y), and each row containing one of its vertices? Is the first vertex repeated at the end (to "close" the polygon), or is this implicit? If you put a complete example MCVE, will be easier to receive answers.
– carlosfigueira
And for convexity, you can calculate all angles from the adjacent 3-vertex sets based on http://stackoverflow.com/questions/1211212/how-to-calculate--angle-from-three-points, and if all are smaller than 180, your polygon will be convex.
– carlosfigueira
@carlosfigueira I put an example.
– Wagner Jorge
Wagner, Carlos already gave you the answer about the polygon being regular. I suggest you ask a different question about being convex, in case you can’t solve it with Carlos' tips. He’ll probably respond in no time. :)
– Molx