Initialize array of arrays

Hi!
I’m creating a matrix of arrays:

hist = Array{Array{Int64, 1}, 2}(x, y)

and filling some of its elements, but others will be left uninitialized.
I was wondering if there is some syntax available to default-initialize all the Array{Int64, 1} elements, so they do not show as #undef.
I could iterate over all elements, checking for those that were left uninitialized isdefined(hist, i*j) and then initializing them to empty arrays hist[i, j] = Array{Int64, 1}(), but I was wondering if there is a better way of doing this.

Basically, I’m trying to replicate C++ RAII idiom, so I don’t get UndefErrors

Thanks!

2 Likes

You can do

julia> fill(Int[], 2, 3)
2×3 Array{Array{Int64,1},2}:
 []  []  []
 []  []  []

if it is fine to have the same empty vector everywhere or

julia> [Int[] for i=1:2, j=1:3]
2×3 Array{Array{Int64,1},2}:
 []  []  []
 []  []  []

if you need distinct empty vectors. The difference mostly matters if you intend to push data into the elements rather than replace them with new vectors.

9 Likes

Ooohhh, right fill() can be used to construct&initialize arrays.
Thanks! This was exactly what I was looking for.

Note, as said above, that fill will initialize the array of arrays with the same array:

julia> a = fill(Int[],2,2)
2×2 Array{Array{Int64,1},2}:
 Int64[]  Int64[]
 Int64[]  Int64[]

julia> push!(a[1,1],1)
1-element Array{Int64,1}:
 1

julia> a
2×2 Array{Array{Int64,1},2}:
 [1]  [1]
 [1]  [1]

2 Likes