Search code examples
arraysjuliaallocation

Pre-allocation of array of array


In julia, one can pre-allocate an array of a given type and dims with

A = Array{<type>}(undef,<dims>)

example for a 10x10 matrix of floats

A = Array{Float64,2}(undef,10,10)

However, for array of array pre-allocation, it does not seem to be possible to provide a pre-allocation for the underlying arrays. For instance, if I want to initialize a vector of n matrices of complex floats I can only figure this syntax,

A = Vector{Array{ComplexF64,2}}(undef, n)

but how could I preallocate the size of each Array in the vector, except with a loop afterwards ? I tried e.g.

A = Vector{Array{ComplexF64,2}(undef,10,10)}(undef, n)

which obviously does not work.


Solution

  • In the cases like you have described you need to use comprehension:

    a = [Matrix{ComplexF64}(undef, 2,3) for _ in 1:4]
    

    This allocates a Vector of Arrays. In Julia's comprehension you can iterate over more dimensions so higher dimensionality is also available.