How to Compute Distance Matrices in Julia
Overview
The Distance Matrix is commonly used in simulations based on Particle Dynamics and Moving Agents, but it is often difficult to find a ready-made function for this purpose, and coding it from scratch can be daunting. In Julia, you can easily calculate a distance matrix using the pairwise()
function and the Euclidean()
function from the Distances
package1.
The dims
option allows you to specify the direction of rows and columns. As you can see, given a $\mathbb{R}^{5 \times 3}$ matrix, it is possible to calculate the distances of $5$dimensional vectors for $3$ instances or the distances of $3$dimensional vectors for $5$ instances.
Code
using Distances
coordinate = [2 3 4; 5 1 3; 1 7 5; 1 7 6; 2 4 3]
pairwise(Euclidean(), coordinate; dims=1)
pairwise(Euclidean(), coordinate; dims=2)
The result of running the above code is as follows.
julia> using Distances
julia> coordinate = [2 3 4; 5 1 3; 1 7 5; 1 7 6; 2 4 3]
5×3 Array{Int64,2}:
2 3 4
5 1 3
1 7 5
1 7 6
2 4 3
julia> pairwise(Euclidean(), coordinate; dims=1)
5×5 Array{Float64,2}:
0.0 3.74166 4.24264 4.58258 1.41421
3.74166 0.0 7.48331 7.81025 4.24264
4.24264 7.48331 0.0 1.0 3.74166
4.58258 7.81025 1.0 0.0 4.3589
1.41421 4.24264 3.74166 4.3589 0.0
julia> pairwise(Euclidean(), coordinate; dims=2)
3×3 Array{Float64,2}:
0.0 9.64365 7.07107
9.64365 0.0 3.31662
7.07107 3.31662 0.0