Multidimensional Arrays Initialization and Assignments

I am trying to create empty multidimensional arrays where each element of the array is a 2d Float64 array with variable numbers of elements.
I am finding this very counter-intuitive and I am still extremely confused with how Julia deals with this easy task. I read the manual and documentation a few times and could not find a simple, clear answer for this.

I tried several different ways found here and there on the Internet and none of them worked.

A = [Float64[] for i = 1:2 for j = 1:4]

correctly creates a 2 by 4 empty array where every element is a 1-d Float64 array. Since I need 2d arrays I tried the following:

A = [Array{Float64,2}[] for i=1:2 for j=1:4]

which results in the unexpected (for me) behavior of creating an array containing Array{Array{Float64,2},1} type of elements. Again not what I was looking for.
I understand this should be trivial but apparently it is not, at least for me.

You can do A = [Array{Float64}(undef,0,0) for i=1:2, j=1:4] to create a 2×4 array where every element is an empty 2d array, for example.

3 Likes

Thank you. This seems to be exactly what I need. Can you please explain why is this different than calling:

A = [Array{Float64,2}[] for i=1:2 for j=1:4]

This is extremely counter-intuitive for me.

The syntax T[] creates an Array{T, 1}, that’s all.

For example: Float64[] creates an Array{Float64, 1}. By analogy, Array{Float64, 2}[] creates an Array{Array{Float64, 2}, 1},

4 Likes