Skip to content

Instantly share code, notes, and snippets.

@ayota
Last active August 29, 2015 14:14
Show Gist options
  • Save ayota/4d2a6eb131a842aca531 to your computer and use it in GitHub Desktop.
Save ayota/4d2a6eb131a842aca531 to your computer and use it in GitHub Desktop.
hwk 3 prob 5 a
norm <- function(x) {
norm <- sqrt(sum(x^2))
return(norm)
}
x.1 <- c(-2,1,0)
x.2 <- c(1,-1,1)
y.1 <- c(0,1,0)
y.2 <- c(1,1,2)
#making lines into planes, finding normal vector between them
x.1 <- c(-2,1,0)
x.2 <- c(1,-1,1)
y.1 <- c(0,1,0)
y.2 <- c(1,1,2)
#find normal vector
mm<-cbind(x.2,y.2)
N <- sapply(1:3,function(x)det(mm[-x,])*(2*(x%%2)-1))
xy <- x.1 - y.1
dist <- norm(t(xy)%*%N)/norm(N)
#minimizing the distance function
linesDist <- function(x1, x2, y1, y2) {
dist <- function(s1, s2) {
d <- sqrt(t(x1 + s1*x2 - (y1 + s2*y2)) %*% (x1 + s1*x2 - (y1 + s2*y2)))
return(d)}
start <- cbind(seq(-100,100,.01),seq(-100,100,.01))
m<-min(mapply(function(s1,s2) nlm(dist,s1,s2)$minimum,start[,1],start[,2]))
return(m)}
linesDist(x.1,x.2,y.1,y.2)
#[1] 1.603579
dist
# 1.603567
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment