Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a vector of tuples in an array in JULIA

Tags:

julia

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

like image 212
Luca Monno Avatar asked Dec 23 '22 15:12

Luca Monno


1 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
like image 178
mcabbott Avatar answered Dec 27 '22 18:12

mcabbott