3
votes

So I am trying to re-size vector of vectors in Julia like this:

A = [Vector{Any}() for i in 1:6]
a, b, c, d, e, f, g, h = 3, 4, 5, 6, 7, 8, 9, 10
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

I am getting this 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 ./:?

Any help please?

1
Please don't post the same questions on multiple forums, it duplicates the work of volunteers taking time answering them, see discourse.julialang.org/t/vector-re-size/13733, discourse.julialang.org/t/vector-of-vectors/13748/2 - fredrikekre
I am sorry about that. There was no reply to that post on discourse, so I had to post it here, since there are many members on Stackoverflow who are very active here but not that much on discourse. - Isai

1 Answers

3
votes

There are two problems with your code.

Problem 1. resize! changes the size of the vector but does not initialize its elements. If vector has element type Any then the entries will be #undef which means uninitialized. You have to initialize them first before accessing.

Here is an example:

julia> A = Any[]
0-element Array{Any,1}

julia> resize!(A, 1)
1-element Array{Any,1}:
 #undef

julia> resize!(A[1], 1) # you get an error
ERROR: UndefRefError: access to undefined reference
Stacktrace:
 [1] getindex(::Array{Any,1}, ::Int64) at .\array.jl:549

julia> A[1] = Any[]
0-element Array{Any,1}

julia> A
1-element Array{Any,1}:
 Any[]

julia> resize!(A[1], 1) # now it works
1-element Array{Any,1}:
 #undef

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

Problem 2. Your code will not work under Julia 1.0, because you are trying to modify a global variable inside a loop (e.g. a in line a += 1). Wrap your code inside a function or let block to make it not throw an error.