Josie G
Josie G

Reputation: 145

Form a distance matrix in Julia

I'm given a 20*122 matrix p. Each row of matrix is a 20-dim vector. I want to calculate the distance between each vector and form a distance matrix. Here's my code

mul = []
for i in 1:size(p,1)
    push!(mul,norm(p[1,:]-p[i,:]))
end
mul = transpose(tiedrank(mul))
for i in 2:size(p,1)
    for j in 1:size(p,1)
        mul2 = []
        push!(mul2,norm(p[i,:]-p[j,:]))
    end
    mul = vcat(mul,tiedrank(mul2)')
end
mul

I got the error that

UndefVarError: mul2 not defined

How to fix this code?

Upvotes: 1

Views: 1023

Answers (3)

AboAmmar
AboAmmar

Reputation: 5559

One of the nice features of Julia is that you can copy-paste an efficient algorithm from a paper and get it working in a 1-to-1 lines of code.

enter image description here

Here is how you might write that in Julia:

p = rand(20, 122);
G = p * p';
D = sqrt.(diag(G) .+ diag(G)' .- 2 .* G);

This is exactly what you get if you use a package like Distances.jl,

using Distances
D = pairwise(Euclidean(), p')

Note that I used p = p' in both methods because you wanted the distance between row vectors.

Upvotes: 1

Benoit Pasquier
Benoit Pasquier

Reputation: 2995

Use the Distances.jl package:

julia> using Distances

julia> p = rand(20, 122)
20×122 Matrix{Float64}:
 0.830266   0.938016  …  0.919852  0.549327
 0.337624   0.863166     0.917122  0.601121
 ⋮                    ⋱  ⋮
 0.122402   0.85733      0.111437  0.694836
 0.0791678  0.763321     0.968744  0.279512

julia> pairwise(Euclidean(), p)
122×122 Matrix{Float64}:
 0.0      2.21042  …  1.58048  1.94589
 2.21042  0.0         1.71839  1.95506
 ⋮                 ⋱  ⋮
 1.58048  1.71839  …  0.0      1.73247
 1.94589  1.95506     1.73247  0.0

Upvotes: 1

Ted Dunning
Ted Dunning

Reputation: 1907

You define mul2 inside the loop. Move the definition one line earlier.

Upvotes: 0

Related Questions