Re: [S] Points in or out of polygon

Peter Perkins (peter@caliban.ucsd.edu)
Wed, 04 Mar 1998 10:46:18 -0800

> I have a need to determine whether or not points are in or out of
> arbitrarily shaped and located polygons. Has anyone written an S-PLUS
> function that would do something like, given the x-y coordinates of
> the vertices of a polygon, determine whether the x-y coordinates of
> another point are inside or outside of it?
>
this should do what you want:

region.inside <- function(test, vertices)
{
# determine whether test points are inside a simply closed polygon.
# this routine uses EUCLIDEAN geometry, not SPHERICAL.
#
# test: matrix (or 2-vector) of test points
# vertices: matrix of polygon vertices, last vertex same as first
#
# col1 = x-coords, col2 = y-coords
#
n <- nrow(vertices) - 1
if(!is.matrix(test)) test <- matrix(test, nrow = 1, byrow = T)
#
# translate to coords centered at each test point
x <- - outer(test[, 1], vertices[1:n, 1], "-")
y <- - outer(test[, 2], vertices[1:n, 2], "-") #
#
# tan(theta) = (v1 x v2) / (v1 * v2)
i2 <- c(2:n, 1)
theta <- atan(x * y[, i2] - y * x[, i2], x * x[, i2] + y * y[,
i2]) #
#
# sum angles about each test point
theta <- abs(theta %*% rep(1, n))
ifelse(abs(theta - 2 * pi) < 1e-06, T, F)
}
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news