在Julia中,找到两个n维向量之间的欧几里德距离有什么简单的方法?
这里有一个简单的方法
n = 10
x = rand(n)
y = rand(n)
d = norm(x-y) # The euclidean (L2) distance
曼哈顿/出租车/L1距离,使用norm(x-y,1)
由于可爱的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}
还有其他可用的距离:
更多详情请查看该包在Github上的页面。
Distances
包。我认为通过使用 norm()
函数 OP 的问题已经得到了足够的回答,但知道这个包还是很有用的。 - Zhubarbnorm(rand((4,4,4)) - rand((4,4,4)))
将失败。 - Bill Grossnorm(x) = sqrt(sum(x.^2))
更适用于其他L1、L2、L3等规范。
norm(x; L=2) = sum(abs.(x).^L) ^ (1/L)
对于两个n维向量之间的欧几里德距离,只需调用 norm(x-y)
。
sqrt(sum(x.^2))
创建了一个不必要的中间数组。更好的写法是 sqrt(sum(abs2, x))
。 - DNF
using LinearAlgebra
。 - Amade