Vector of vectors

Hi everyone!
I am trying to resize the inner vectors but I am confused as to what I am doing wrong.
A = [Vector{Any}() for i in 1:6]
and then:

a, b, c, d = 3, 4, 5, 6
for tt = 1:6
    a+=1
    resize!(A[tt], a)
    for rr = 1:a
        b+=1
        resize!(A[tt][rr], b)
        for tt2 = 1:b
            resize!(A[tt][rr][tt2], b)
        end
    end
end

Error:

UndefRefError: access to undefined reference Stacktrace: [1] getindex(::Array{Any,1}, ::Int64) at ./array.jl:549 [2] macro expansion at ./In[70]:7 [inlined] [3] anonymous at ./<missing>:?

Thanks!

Don’t post the same question on multiple forums without linking them to each other, arrays - Resize Vectors Julia - Stack Overflow.

It is also helpful to make the example as minimal as possible. This has the benefit that you often realize yourself what is wrong.

Here is a smaller example that shows the same behaviour:

julia> A = [Vector{Any}(undef, 1)]
1-element Array{Array{Any,1},1}:
 [#undef]

julia> A[1][1]
ERROR: UndefRefError: access to undefined reference
Stacktrace:
[...]

which is what happens when you call resize!(A[tt][rr], b) in your code: The entry A[tt][rr] is not initialized to anything, so you can not extract it and resize it.

Here is one, minimal, modification,that I think does what you want:

A = [Vector{Any}() for i in 1:6]
a, b, c, d = 3, 4, 5, 6
for tt = 1:6
    a+=1
    resize!(A[tt], a)
    for rr = 1:a
        b+=1
        A[tt][rr] = Vector{Any}(undef, b) # instead of resize!(A[tt][rr], b)
        for tt2 = 1:b
            A[tt][rr][tt2] = Vector{Any}(undef, b) # instead of resize!(A[tt][rr][tt2], b)
        end
    end
end
1 Like