Created
November 20, 2018 19:43
-
-
Save leungi/d0564a379562316a7f225432e23b703c to your computer and use it in GitHub Desktop.
Finding intersections between 2 lines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stackoverflow.com/questions/20519431/finding-point-of-intersection-in-r | |
set.seed(1) | |
x1=rnorm(100,0,1) | |
x2=rnorm(100,1,1) | |
# Find points where x1 is above x2. | |
above<-x1>x2 | |
# Points always intersect when above=TRUE, then FALSE or reverse | |
intersect.points<-which(diff(above)!=0) | |
# Find the slopes for each line segment. | |
x1.slopes<-x1[intersect.points+1]-x1[intersect.points] | |
x2.slopes<-x2[intersect.points+1]-x2[intersect.points] | |
# Find the intersection for each segment. | |
x.points<-intersect.points + ((x2[intersect.points] - x1[intersect.points]) / (x1.slopes-x2.slopes)) | |
y.points<-x1[intersect.points] + (x1.slopes*(x.points-intersect.points)) | |
plot(x1,type='l') | |
lines(x2,type='l',col='red') | |
points(x.points,y.points,col='blue') | |
x1[intersect.points] | |
x2[intersect.points] | |
setdiff(floor(x.points), intersect.points) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment