Home > front end >  extracting elements of vector of named tuples into matrix in Julia
extracting elements of vector of named tuples into matrix in Julia

Time:05-09

Suppose results is a vector of tuple with length M where typeof(result) = Vector{NamedTuple{(:x, :p, :step), Tuple{Vector{Float64}, Float64, Int64}}}.

p is also a vector of length N where typeof(results[1].p) = Vector{Float64}. I want to extract the first N-1 elements of all the p inside results and express it as an M x (N-1) matrix. I know how to do it in a for loop, but is there a more element way of doing it?

CodePudding user response:

These should both do what you ask but they return an (N-1 x M) matrix and I think they are very similar

hcat(map(x->x.p[1:N-1], results)...)

hcat([x.p[1:N-1] for x in results]...)

For the (M x N-1) output

vcat(map(x->x.p[1:N-1]', results)...)

vcat([x.p[1:N-1]' for x in results]...)

should work but it is a bit slower.

  • Related