Convert a vector of tuples in an array in JULIA

Viewed 1927

I'm quite new to Julia and I'm trying to convert a vector of tuples in array. Here's an example

using Statistics
a = randn((10, 100))
q = (0.05, 0.95)
conf_intervals = [quantile(a[i,:], q) for i in 1:10]

and conf_intervals is a 10-element Vector{Tuple{Float64, Float64}}.

The expected result should be a 10×2 Matrix{Float64}

I tried splatting conf_intervals with [conf_intervals...] but the vector doesn't change.

Thank you very much

2 Answers

You can use a comprehension:

mat2x10 = [tup[k] for k in 1:2, tup in conf_intervals]
mat10x2 = [tup[k] for tup in conf_intervals, k in 1:2]

Or you can just re-interpret the same memory. This is more fragile -- it won't work for all vectors of tuples, e.g. Any[(i, i^2/2) for i in 1:10]. But for Vector{Tuple{Float64, Float64}}:

if VERSION >= v"1.6"
    reinterpret(reshape, Float64, conf_intervals)
else
    reshape(reinterpret(Float64, conf_intervals), 2, :)
end
mat2x10 == ans  # true

You need to use collect to convert tuples to vectors, and then you can combine them:

julia> hcat(collect.(conf_intervals)...)
2×10 Matrix{Float64}:
 -1.59757  -2.10057  -1.4437   -1.32868  -1.10686  -1.41256  -1.5696   -1.67288  -1.51947  -1.72257
  1.24604   1.61692   1.77684   1.3599    1.90853   1.30831   1.10667   1.58356   1.56811   1.70685

If you need to transpose the result, add an apostrophe ' end the end of the command

Related