Array of arrays construction

Hi,

The following is how I usually construct an array. Each element of array temp is an array that has different number of elements (which I assign later).

temp = Array{Array{Float64},1}(undef,10)
for ii in 1:10
   temp[ii] = Float64[]
end

Is there any way to reduce this code into one line? for example, by replacing undef operator by Float64[], or anything like that?

Use a comprehension.

[Float64[] for i in 1:10]
4 Likes

This is great! Thank you so much!

Or, if you want to save a few more characters

fill(Float64[], 10)

Edit: wrong, see below

1 Like

This fills the array with 10 references to the same empty array, which probably isn’t what you want. There’s a warning in the docstring about this I believe.

4 Likes

You’re right good catch, I retract my answer. There is indeed a warning about this in the docs.

One follow-up question.

[Float64[] for i in 1:10]

This gives me a vector of vectors (1-D array). How can I make a vector of 2-D arrays?

Edit: Oh, well, that link is about matrix of vectors, which is interesting but not what was asked here.

See Initialize array of arrays.

1 Like

Float64[] is an alias for Array{Float64,1}(). So you can use Array{Float64,2}(undef,r,c). It is necessary to specify undef and the dimensions for arrays with more than one dimension. Depending on your use case it might be simpler to use x = [fill(0.0,2,2) for i in 1:10]

You can also initialize as follows if you do not want the sub arrays to be predefined.

x = Array{Array{Float64,2},1}(undef,2)

x[1] = rand(3,3)

x[2] = rand(2,2)
push!(x, rand(1,3))# push additional arrays
2 Likes

Thanks! I appreciate your reply.

1 Like