How to get the intersection point of two vector?

前端 未结 2 570
我在风中等你
我在风中等你 2020-12-19 04:17
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 vec

2条回答
  •  借酒劲吻你
    2020-12-19 05:06

    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

提交回复
热议问题