Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading