BambOo
BambOo

Reputation: 425

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.

Upvotes: 4

Views: 1322

Answers (2)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

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.

Upvotes: 2

phipsgabler
phipsgabler

Reputation: 20950

Remember that "allocate" means "give me a contiguous chunk of memory, of size exactly blah". For an array of arrays, which is really a contiguous chunk of pointers to other contiguous chunks, this doesn't really make sense in general as a combined operation -- the latter chunks might just totally differ.

However, by stating your problem, you make clear that you actually have more structural information: you know that you have n 10x10 arrays. This really is a 3D array, conceptually:

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

At that point, you can just take slices, or better: views along the first axis, if you need an array of them:

[@view A[i, :, :] for i in axes(A, 1)]

This is a length n array of AbstractArrays that in all respects behave like the individual 10x10 arrays you wanted.

Upvotes: 3

Related Questions