Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the intersection point of two vector?

Tags:

r

a = c(1,5,2,6,3,6,3,5,7)
b= c(5,3,5,7,2,6,9,3,6)
plot(a,type = "l")
lines(b)

Are there any function to get all the intersection points of two vectors? enter image description here

like image 776
LK Yeung Avatar asked Feb 08 '14 15:02

LK Yeung


2 Answers

Using R's spatial facilities:

library(sp)     ## Provides basic spatial classes/methods, incl. SpatialLines
library(rgeos)  ## Supports topological operations, including intersection

## Read in data and wrap them up as SpatialLines objects    
a = c(1,5,2,6,3,6,3,5,7)
b = c(5,3,5,7,2,6,9,3,6)
SL1 <- SpatialLines(list(Lines(Line(cbind(seq_along(a),a)), "A")))
SL2 <- SpatialLines(list(Lines(Line(cbind(seq_along(b),b)), "B")))

## Find intersections
coords <- coordinates(gIntersection(SL1, SL2))

## Check that it worked
plot(a,type = "l")
lines(b)
points(coords, col="red", pch=16)

enter image description here

like image 140
Josh O'Brien Avatar answered Oct 14 '22 12:10

Josh O'Brien


a = c(1,5,2,6,3,6,3,5,7)
b= c(5,3,5,7,2,6,9,3,6)

plot(a,type = "l")
lines(b)

i <- seq_along(a)

inter0 <- i[(a-b)==0]

as <- split(a, cut(i, c(0,inter0,Inf)))
bs <- split(b, cut(i, c(0,inter0,Inf)))

m <- 0
xs <- ys <- numeric(length(a))

for (k in seq_along(as)) {
  int <- which(diff(sign(as[[k]]-bs[[k]])) != 0)
  left <- cbind(as[[k]][int], bs[[k]][int])
  right <- cbind(as[[k]][int+1], bs[[k]][int+1])
  d <- right-left
  x <- (left[,1]-left[,2] )/(d[,2]-d[,1])
  y <- left[,1]+d[,1]*x
  x <- x+int+m
  xs[(m+1):(m+length(x))] <- x 
  ys[(m+1):(m+length(y))] <- y 
  m <- m+length(as[[k]])
}

ys <- ys[xs!=0]
xs <- xs[xs!=0]
points(xs,ys,col="red")

enter image description here

like image 7
Roland Avatar answered Oct 14 '22 12:10

Roland