[R] x, y for point of intersection

Monica Pisica pisicandru at hotmail.com
Wed Nov 23 15:35:13 CET 2011


Hi everybody,

Thank you so much for your answers. The easiest and most straight forward solution is using the function segm_dist from package "pracma" as suggested by Hans Borchers. 

Thanks again and Happy Thanksgiving for those who celebrate!

Monica
----------------------------


Message: 99

Date: Wed, 23 Nov 2011 08:11:22 +0000

From: Hans W Borchers <hwborchers at googlemail.com>

To: <r-help at stat.math.ethz.ch>

Subject: Re: [R] x, y for point of intersection

Message-ID: <loom.20111123T085346-542 at post.gmane.org>

Content-Type: text/plain; charset="utf-8"



Monica Pisica <pisicandru <at> hotmail.com> writes:



> Hi everyone,

> 

> I am trying to get a point of intersection between a

> polyline and a straight line ?.. and get the x and y coordinates of this
point.

> For exemplification consider this:

> 

set.seed(123)

k1 <-rnorm(100, mean=1.77, sd=3.33)

k1 <- sort(k1)



q1 <- rnorm(100, mean=2.37, sd=0.74)

q1 <- sort(q1, decreasing = TRUE)



plot(k1, q1, xlim <- c((min(k1)-5), (max(k1)+5)), type="l")



xa <- -5; ya <- 2

xb <- 12; yb <- 4



lines(c(xa, xb), c(ya, yb), col = 2)

> 

> I want to get the x and y coordinates of the intersection of the 2 lines
...

> 

> m <- (ya-yb)/(xa-xb)

> b <- ya-m*xa

> ln <- loess(q1~k1)

> lines(ln)

> 

> It is clear that the x, y will satisfy both linear

> equations, y = m*x + b and the ln polyline ?.. but while I can visualize
the

> equation of the straight line ? I have problems with the polyline. I will

> appreciate any ideas to solve this problem. I thought it a trivial
solution 

> but it seems I cannot see it.



You could apply the function segm_distance in package 'pracma'. If the 

distance between two segments is 0, it returns the intersection point:



p1 <- c(xa, ya); p2 <- c(xb, yb)

for (i in 2:100) {

p3 <- c(k1[i-1], q1[i-1]); p4 <- c(k1[i], q1[i])

s <- segm_distance(p1, p2, p3, p4)

if (s$d == 0) break

}

s$p # 0.2740154 2.6204724

points(s$p[1], s$p[2], pch="+", col="red")



> Thanks,

> Monica

>


 		 	   		  


More information about the R-help mailing list