两个n维向量之间的欧几里德距离

15
在Julia中,找到两个n维向量之间的欧几里德距离有什么简单的方法?
3个回答

20

这里有一个简单的方法

n = 10
x = rand(n)
y = rand(n)
d = norm(x-y)  # The euclidean (L2) distance

曼哈顿/出租车/L1距离,使用norm(x-y,1)


4
在 Julia 1.0 中,您需要先调用 using LinearAlgebra - Amade

14

由于可爱的Distances程序包,这很容易实现:

Pkg.add("Distances") #if you don't have it
using Distances
one7d = rand(7)
two7d = rand(7)
dist = euclidean(one7d,two7d)

如果你有两个9维列向量矩阵,你可以使用colwise函数得到每对对应向量之间的距离:

thousand9d1 = rand(9,1000)
thousand9d2 = rand(9,1000)
dists = colwise(Euclidean(), thousand9d1, thousand9d2)
#returns: 1000-element Array{Float64,1}

如果您想要每个列向量的大小,也可以将其与单个向量(例如原点)进行比较。

origin9 = zeros(9)
mags = colwise(Euclidean(), thousand9ds1, origin9)
#returns: 1000-element Array{Float64,1}

还有其他可用的距离:

  • 平方欧几里得
  • 曼哈顿距离
  • 切比雪夫距离
  • 闵可夫斯基距离
  • 汉明距离
  • 余弦距离
  • 相关系数
  • 卡方距离
  • Kullback-Leibler散度
  • Jensen-Shannon散度
  • 马氏距离
  • 平方马氏距离
  • Bhattacharyya距离
  • Hellinger距离

更多详情请查看该包在Github上的页面。


3
谢谢提及 Distances 包。我认为通过使用 norm() 函数 OP 的问题已经得到了足够的回答,但知道这个包还是很有用的。 - Zhubarb
1
这也适用于高于2维的数组(norm仅支持1或2维数组)。例如,norm(rand((4,4,4)) - rand((4,4,4)))将失败。 - Bill Gross

0
计算范数而不使用任何导入,只需简单地
norm(x) = sqrt(sum(x.^2))

更适用于其他L1、L2、L3等规范。

norm(x; L=2) = sum(abs.(x).^L) ^ (1/L)

对于两个n维向量之间的欧几里德距离,只需调用 norm(x-y)


1
sqrt(sum(x.^2)) 创建了一个不必要的中间数组。更好的写法是 sqrt(sum(abs2, x)) - DNF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接