2014-02-08 2 views
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두 벡터의 교점을 얻는 방법?

+0

당신이 "벡터의 교차점"무엇을 의미합니까? 그래프가 교차하는 점은 무엇입니까? – twin

+0

예. 그래프가 교차하는 점. –

+1

글쎄, 너는 나에게 가졌어. 그것들은 수학적 의미의 벡터가 아니야. 만약 그렇다면, 원점에서 9 라인의 점까지의 두 줄이 교차하는지 알아내는 방법을 물어볼거야. -0. 더 흥미로운 문제. –

답변

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) 

enter image description here

+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

+0

+1에 대한 해결책 – rawr

+2

충격! OK, Roland, 저는 여러분이 데이터 집합에 정수 좌표 만 있다는 가정하에 이것을 쓰고 싶습니다. 'i [(a-b) == 0]'!! 그렇지 않으면, 매우 잘 수행 –

관련 문제