2014-09-12 122 views
0

我有一条分割线,在2D中有大约80个点,而点P(X/Y)不在此线上。从一个点到一条分割线的最短距离

我需要知道在哪里点P”是在这条线,这也在P.

的最短距离有一个简单的方法来计算呢?

编辑:

输入文件:

str(coords) 
'data.frame': 80 obs. of 2 variables: 
$ x: num 2140 2162 2169 2167 2158 ... 
$ y: num 1466 1437 1412 1390 1369 ... 

str(point) 
'data.frame': 1 obs. of 2 variables: 
$ x: num 1778 
$ y: num 1911 

输出文件:

上分割行点

+1

你知道会是什么太棒了?带有样本输入和期望输出的[可重现示例](http://stackoverflow.com/questions/5963269/how-to-make-a- great-r-reproducible-example)。只是要求包裹建议被认为是SO的主题。 – MrFlick 2014-09-12 15:20:13

+0

使用标准几何图形来查找从点到实线的距离,然后如果该点不在一个线段上,请找到最接近的线段端点。这与'R'无关。 – 2014-09-12 15:45:38

+0

如果你发布公式,你更有可能得到如何把它放在代码中。 – rnso 2014-09-12 15:56:20

回答

0

我有解决方案现在...即使它是不是很有效。 也许有人认为这很有用。 我改变了P的坐标以获得更好的结果。

distance <- data.frame(dist = NA) 
coordinates <- data.frame(x=NA,y=NA) 

coords <- data.frame(x=c(2140,2162,2169,2167,2158),y=c(1466,1437,1412,1390,1369)) 
point <- data.frame(x=2130,y=1400) 


for(j in 1:(length(coords[,1]))){ 
    distance[2*j-1,1] <- sqrt((coords[j,1]-point[1,1])^2+(coords[j,2]-point[1,2])^2) 
    coordinates[2*j-1,] <- coords[j,] 
} 

计算从点P的所有垂直距离和点P的这些趴在分割行

for(j in 1:(length(coords[,1])-1)){ 
d <- abs((coords[j+1,1]-coords[j,1])*(coords[j,2]-point[1,2])- 
     (coords[j,1]-point[1,1])*(coords[j+1,2]-coords[j,2]))/ 
     sqrt((coords[j+1,1]-coords[j,1])^2+(coords[j+1,2]-coords[j,2])^2) 

t <- abs(((point[1,1]-coords[j,1])*(coords[j+1,1]-coords[j,1])+ 
     (point[1,2]-coords[j,2])*(coords[j+1,2]-coords[j,2]))/ 
     ((coords[j+1,1]-coords[j,1])^2+(coords[j+1,2]-coords[j,2])^2)) 
x <- coords[j,1]+t*(coords[j+1,1]-coords[j,1]) 
y <- coords[j,2]+t*(coords[j+1,2]-coords[j,2]) 

if(min(coords$x[j],coords$x[j+1]) <= x && x <= max(coords$x[j],coords$x[j+1]) && 
    min(coords$y[j],coords$y[j+1]) <= y && y <= max(coords$y[j],coords$y[j+1])){ 
    if(coords[j,] != c(x,y) && coords[j+1,] != c(x,y)){ 
    distance[2*j,1] <- d 
    coordinates[2*j,] <- c(x,y) 
    } 
} 
} 

位置最小距离”的坐标:

p <- which(distance==min(distance, na.rm=TRUE)) 
coordinates[p,] 
相关问题