# Joining arrays of vectors of abritrary lengths

Hi,

I need to use arrays in which each element is a vector of arbitrary length. In itself, it works fine but when I try to append! an element to another array of vectors, it appends the vector to every elements of the target array. Obviously this is not what I want. Any ideas?

Creating a deepcopy of the element, appending to it and putting the deepycopy as the element works, but it is way too slow for what I am doing.

Here’s a working example of the problem:

``````stack = Array{Any}(undef, 2, 3, 3)
fill!(stack, Float64[])

stack[1, 1, 1] = [1.0, 2.0, 3.0]

merged_stack = Array{Any}(undef, 3, 3)
fill!(merged_stack, Float64[])

new_element = getindex(merged_stack, 1, 1)
merged_stack[1, 1] = append!(merged_stack[1, 1], stack[1, 1, 1])
println(merged_stack)
``````

``````julia> merged_stack = Array{Any}(undef, 3, 3)
3×3 Matrix{Any}:
#undef  #undef  #undef
#undef  #undef  #undef
#undef  #undef  #undef

julia> fill!(merged_stack, Float64[])
3×3 Matrix{Any}:
Float64[]  Float64[]  Float64[]
Float64[]  Float64[]  Float64[]
Float64[]  Float64[]  Float64[]

julia> append!(merged_stack[1,1],[1.0,2.0])
2-element Vector{Float64}:
1.0
2.0

julia> merged_stack
3×3 Matrix{Any}:
[1.0, 2.0]  [1.0, 2.0]  [1.0, 2.0]
[1.0, 2.0]  [1.0, 2.0]  [1.0, 2.0]
[1.0, 2.0]  [1.0, 2.0]  [1.0, 2.0]
``````

The `fill!` fills `merged_stack` with the same object. Alle the empty arrays `Float64[]` are a single object.
There are several ways to achieve what you need, typically, I don’t have the most efficient way, but others will provide them.
You can do with a loop for example:

``````julia> merged_stack = Array{Vector{Float64}}(undef, 3, 3)
3×3 Matrix{Vector{Float64}}:
#undef  #undef  #undef
#undef  #undef  #undef
#undef  #undef  #undef

julia> for index in eachindex(merged_stack)
merged_stack[index]=Float64[]
end

julia> append!(merged_stack[1,1],[1.0,2.0])
2-element Vector{Float64}:
1.0
2.0

julia> merged_stack
3×3 Matrix{Any}:
[1.0, 2.0]  Float64[]  Float64[]
Float64[]   Float64[]  Float64[]
Float64[]   Float64[]  Float64[]
``````
2 Likes

I added the initialization, which was `Any` in your case. It’s best to use the Type you are using later.

Thank you this is exactly what I needed!

1 Like