How to convert a Tuple{Array{Float64,1},Array{Float64,1}} to Array{Tuple{Float64,Float64},1} in julia

Viewed 49

How may I convert a Tuple{Array{Float64,1},Array{Float64,1}} to Array{Tuple{Float64,Float64},1} ?

Code

#Sampling
function sam()
    x = range(0, 10.0, length = 9) |> collect
    y = range(0, 10.0, length = 9) |> collect
    return (x,y)
end
xy = sam()
typeof(xy)

The code above returns this output:

Tuple{Array{Float64,1},Array{Float64,1}}
1 Answers

The easiest thing to do in your situation is to assign the output of your function to two separate variables, like this:

function foo()
    x = [1, 2, 3]
    y = [4, 5, 6]
    return x, y
end

x, y = foo()

See the docs on multiple return values.

Then you can use zip to turn the vectors into an iterator of tuples:

julia> x, y = foo()
([1, 2, 3], [4, 5, 6])

julia> x
3-element Array{Int64,1}:
 1
 2
 3

julia> y
3-element Array{Int64,1}:
 4
 5
 6

julia> z = zip(x, y)
zip([1, 2, 3], [4, 5, 6])

Note that the output of zip is an iterator, rather than an array of tuples. You can either iterate through the elements of the iterator to get the individual tuples,

julia> foreach(println, z)
(1, 4)
(2, 5)
(3, 6)

or you can collect the iterator if you actually need an array of tuples:

julia> collect(z)
3-element Array{Tuple{Int64,Int64},1}:
 (1, 4)
 (2, 5)
 (3, 6)
Related