How to calculate Euclidean distance between a tuple and each tuple in a Vector using map in Julia?

I want to calculate the Euclidean distance between a tuple and each tuple within a Vector in Julia using the map function, like below (but I get two values instead of three):

julia> tups = [
         (1, 3),
         (11, 2),
         (0, 1)
       ];

julia> map((x, y) -> √(sum((x.-y).^2)), tups, (3, 3))
2-element Vector{Float64}:
 2.0
 8.06225774829855

How can I make it work correctly?

>Solution :

The code you’ve written is pretty equal to this:

[
    func((1, 3), 3),
    func((11, 2), 3)
]

The map function iterates over the given collections iter times equal to the lowest length:

julia> length((3, 3)), length(tups)
(2, 3)

So it iterates two times, not three. To make that work, you can repeat the (3, 3), three times or even omit the (3, 3) argument:

julia> map((x, y) -> √(sum((x.-y).^2)), tups, ((3, 3), (3, 3), (3, 3)))
3-element Vector{Float64}:
 2.0
 8.06225774829855
 3.605551275463989

 # OR

julia>  map((x, y) -> √(sum((x.-y).^2)), tups, ((3, 3) for _∈1:3))
3-element Vector{Float64}:
 2.0
 8.06225774829855
 3.605551275463989

 # Or omit the last argument

julia> map(arg -> √((3 - arg[1])^2 + (3 - arg[2])^2), tups)
3-element Vector{Float64}:
 2.0
 8.06225774829855
 3.605551275463989

Leave a Reply