Reputation: 4127
What's an easy way to find the Euclidean distance between two n-dimensional vectors in Julia?
Upvotes: 15
Views: 12620
Reputation: 3734
To compute the norm without any imports, simply
norm(x) = sqrt(sum(x.^2))
More generic for other L1, L2, L3, ... norms
norm(x; L=2) = sum(abs.(x).^L) ^ (1/L)
For Euclidean distance between two n-dimensional vectors just call norm(x-y)
.
Upvotes: 0
Reputation: 4127
This is easily done thanks to the lovely Distances package:
Pkg.add("Distances") #if you don't have it
using Distances
one7d = rand(7)
two7d = rand(7)
dist = euclidean(one7d,two7d)
Also if you have say 2 matrices of 9d col vectors, you can get the distances between each corresponding pair using colwise:
thousand9d1 = rand(9,1000)
thousand9d2 = rand(9,1000)
dists = colwise(Euclidean(), thousand9d1, thousand9d2)
#returns: 1000-element Array{Float64,1}
You can also compare to a single vector e.g. the origin (if you want the magnitude of each column vector)
origin9 = zeros(9)
mags = colwise(Euclidean(), thousand9ds1, origin9)
#returns: 1000-element Array{Float64,1}
Other distances are also available:
More details at the package's github page here.
Upvotes: 14
Reputation: 11644
Here is a simple way
n = 10
x = rand(n)
y = rand(n)
d = norm(x-y) # The euclidean (L2) distance
For Manhattan/taxicab/L1 distance, use norm(x-y,1)
Upvotes: 20