Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize Vectors Julia

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?

like image 744
Isai Avatar asked Oct 25 '25 01:10

Isai


1 Answers

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.

like image 54
Bogumił Kamiński Avatar answered Oct 27 '25 15:10

Bogumił Kamiński