'extracting elements of vector of named tuples into matrix in Julia
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?
Solution 1:[1]
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.
Solution 2:[2]
The conventional 2-loop comprehension may be 10X faster than vcat for this. You get an M x (N-1) matrix directly.
[results[i].p[j] for i=1:M, j=1:N-1]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Giovanni |
| Solution 2 | AboAmmar |
