Easy way to stack vectors of vectors in Julia
Asked Answered
S

2

6

I would like a way to programmatically "deconstruct" a vector of variable-length vectors in Julia. I do not care about the resulting vector's order.

For example, suppose that my vector of vectors is A = [[1], [2,3], [4,5,6]]. I can deconstruct A by writing vcat(A[1], A[2], A[3]), which returns [1,2,3,4,5,6]. However, if the length of A is large, then this approach becomes cumbersome. Is there a better, more scalable way to obtain the same result?

Seigler answered 23/8, 2022 at 14:4 Comment(0)
S
8

While I would second Przemyslaw's answer for any situation where you can get away with using a lazy representation, maybe a more direct answer to your question is:

julia> vcat(A...)
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6

whenever you feel the need to type out all elements of a collection as function arguments, splatting ... is your friend.

Splatting can however negatively impact performance, so it is generally recommended to use reduce, which has a specialisation for vcat:

julia> reduce(vcat, A)
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6
Sprague answered 23/8, 2022 at 15:7 Comment(0)
H
8

Try Iterators.flatten:

julia> collect(Iterators.flatten(A))
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6

(This yields a lazy representation hence I collected this before showing the output)

Hadfield answered 23/8, 2022 at 14:37 Comment(0)
S
8

While I would second Przemyslaw's answer for any situation where you can get away with using a lazy representation, maybe a more direct answer to your question is:

julia> vcat(A...)
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6

whenever you feel the need to type out all elements of a collection as function arguments, splatting ... is your friend.

Splatting can however negatively impact performance, so it is generally recommended to use reduce, which has a specialisation for vcat:

julia> reduce(vcat, A)
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6
Sprague answered 23/8, 2022 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.