# Q: Vector of vectors of variable lengths

Hello,

What is the recommended/best Julia method to create a vector of vectors of variable lengths?

Current method MWE:

``````# test_vector_of_vectors.jl

begin
vec_of_vecs = [Float64[] for _ in 1:3]
for i = 1:3
push!(vec_of_vecs, 0.0)
end
for i = 1:5
push!(vec_of_vecs, 1.0)
end
for i = 1:7
push!(vec_of_vecs, 2.0)
end

@show vec_of_vecs
end
``````

[In the actual code, the variable length vector are workspace arrays, , all initialized to 0.0, to all be passed to a set of functions.]

I bit more terse:

``````vec_of_vecs = [zeros(Float64,s*2+1) for s in 1:3]
``````

If the individual sizes can be calculated from the index. If not I would do it more like:

``````sizes=[ 7, 3, 5 ]
vec_of_vecs = [zeros(Float64,sizes[s]) for s in 1:3]
``````

Don’t know if this is recommended (by whom) or the best (in what sense). If it is important to have the best performance, because it’s perhaps in a hot loop, my guess is, complete performance depends more on the whole thing you want to do, the context.

Or, to set the values too:

``````vec_of_vecs = [ fill( Float64(s), s*2+1 ) for s in 1:3]
``````

Or slightly more succinct:

``````vec_of_vecs = [zeros(Float64, s) for s in sizes]
``````
3 Likes

``````vec_of_vecs = zeros.(s) # default type is Float64
``````
1 Like

Should be in the flow of examples:

``````vec_of_vecs = zeros.(sizes)
``````
1 Like

Thanks to all who replied.

The broadcasting method suggested by abraemer and ohell is elegant.

``````# test_vector_of_vectors.jl

begin
sizes = Int32[3, 6, 7]
vec_of_vecs = zeros.(sizes)

@show vec_of_vecs
end
``````
``````3-element Vector{Vector{Float64}}:
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
``````
1 Like