Search code examples
arraysinitializationjulia

Initializing an empty array in Julia with a large number of arrays inside


I'm trying to initialize an empty array in Julia 1.1 with 6 elements, where the i-th element consists of 1000 Arrays, which will be filled with a loop. For example, if the i-th element contains 3 Arrays, I can do fill([Array{Float64,1},Array{Float64,1} ,Array{Float64,1}],6,1). But how can I obtain the empty 1000 Arrays without copying Array{Float64,1} 1000 times?


Solution

  • Some examples depending on what you want actually to do:

    Set of empty arrays:

    julia> [[Float64[] for a in 1:3] for b in 1:6]
    6-element Array{Array{Array{Float64,1},1},1}:
     [[], [], []]
     [[], [], []]
     [[], [], []]
     [[], [], []]
     [[], [], []]
     [[], [], []]
    

    An uninitialized three dimensional Array having size 6x3x2 (perhaps having a 3D array is actually more convenient than Array of Arrays of Arrays - depends on your use case):

    julia> Array{Float64,3}(undef, 6, 3, 2)
    6×3×2 Array{Float64,3}:
    [:, :, 1] =
     9.00033e-316  1.52477e-315  1.52473e-315
     7.95655e-316  1.52477e-315  1.52473e-315
     1.52474e-315  8.18796e-316  1.52477e-315
     7.95655e-316  1.52477e-315  1.52474e-315
     1.52474e-315  1.52473e-315  1.52474e-315
     8.03142e-316  1.52473e-315  1.52477e-315
    
    [:, :, 2] =
     7.97808e-316  1.52473e-315  0.0
     8.07774e-316  1.52474e-315  0.0
     1.52474e-315  1.52473e-315  0.0
     1.52474e-315  1.52473e-315  0.0
     7.96305e-316  0.0           0.0
     1.52473e-315  0.0           0.0
    

    Allocated set of uninitialized Arrays:

    julia> [[Vector{Float64}(undef,2) for a in 1:3] for b in 1:6]
    6-element Array{Array{Array{Float64,1},1},1}:
     [[1.60704e-315, 1.60693e-315], [5.93041e-316, 1.69135e-315], [1.69002e-315, 1.69135e-315]]
     [[5.93223e-316, 5.93223e-316], [5.92882e-316, 4.94066e-324], [5.93223e-316, 5.93223e-316]]
     [[5.92884e-316, 2.122e-314], [5.92883e-316, 1.60853e-315], [5.93041e-316, 5.92887e-316]]
     [[1.69002e-315, 5.92885e-316], [1.60705e-315, 1.60693e-315], [5.93041e-316, 1.69136e-315]]
     [[1.69002e-315, 1.69136e-315], [5.93223e-316, 5.93223e-316], [5.92882e-316, 5.93043e-316]]
     [[5.93223e-316, 5.93223e-316], [5.92884e-316, 5.93043e-316], [5.92883e-316, 5.93223e-316]]