如何获取两个向量的交点?

8
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)

有没有函数可以获取两个向量的所有交点? enter image description here


“向量的交点”是什么意思?是指图形相交的点吗? - twin
是的。图形相交的点。 - LK Yeung
1
嗯,你把我搞糊涂了:从数学角度来说,那些不是向量(如果是的话,你会问如何判断两条从原点到九维空间中某个点的直线是否相交的问题) 。这才是一个更有趣的问题。 - Carl Witthoft
欢迎您回答自己的问题,@CarlWitthoft :) - rawr
2个回答

12

使用R的空间分析功能:

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)

输入图像描述


3
我知道会有一些软件包可以做到这一点。 - Roland

7
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


2
震惊!好的,罗兰,我希望 :-) 你写这篇文章时假定数据集中只有整数坐标。i[(a-b)==0] !! 否则,非常棒! - Carl Witthoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接