You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言计算点到线段的垂直距离?

R语言计算点到线段的最短距离

核心逻辑说明

C++里的vec2类型在R中直接用数值向量(比如c(x, y))就能对应,本质就是存储x、y坐标的二维数组。计算点到线段的最短距离分两种情况:

  • 当点在线段上的垂足落在线段内部时,最短距离是垂直距离;
  • 当垂足落在线段延长线上时,最短距离是点到线段最近端点的直线距离。

实现代码

先定义计算距离的函数:

# 计算点到线段的最短距离
point_to_segment_dist <- function(A, B, C) {
  # 计算向量AB和AC
  AB <- B - A
  AC <- C - A
  
  # 计算投影参数t:AC在AB上的投影比例
  t <- sum(AC * AB) / sum(AB * AB)
  
  # 限制t在[0,1]范围内,确定最近点
  t <- max(0, min(1, t))
  
  # 计算垂足/最近点坐标
  closest_point <- A + t * AB
  
  # 计算点C到最近点的欧式距离
  sqrt(sum((C - closest_point)^2))
}

用你提供的示例数据测试并绘图:

# 定义点和线段
A <- c(2, 4)
B <- c(8, 16)
C <- c(3, 11)
C1 <- c(11, 16)

# 计算距离
dist_C <- point_to_segment_dist(A, B, C)
dist_C1 <- point_to_segment_dist(A, B, C1)

# 输出结果
cat("点C到线段AB的最短距离:", round(dist_C, 2), "\n")
cat("点C1到线段AB的最短距离:", round(dist_C1, 2), "\n")

# 绘图展示
plot(1, type = "n", xlim = c(0, 25), ylim = c(0, 25))
points(C[1], C[2], col = "red", pch = 16)
points(C1[1], C1[2], col = "blue", pch = 16)
points(A[1], A[2], pch = 18, cex = 1.2)
points(B[1], B[2], pch = 18, cex = 1.2)
segments(A[1], A[2], B[1], B[2], lwd = 2)
# 绘制点到最近点的连线
closest_C <- A + max(0, min(1, sum((C-A)*(B-A))/sum((B-A)^2))) * (B-A)
segments(C[1], C[2], closest_C[1], closest_C[2], col = "red", lty = 2)
closest_C1 <- A + max(0, min(1, sum((C1-A)*(B-A))/sum((B-A)^2))) * (B-A)
segments(C1[1], C1[2], closest_C1[1], closest_C1[2], col = "blue", lty = 2)

结果解释

  • 点C的垂足在线段AB内部,最短距离为垂直距离,计算结果约为2.24;
  • 点C1的垂足落在AB的延长线上(靠近B端),最短距离为C1到B点的直线距离,结果为3.00。

内容的提问来源于stack exchange,提问作者LGH14

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:52:24