multidimensional-arrayjulia

Array comprehension of array-valued function in Julia - inner dimensions somehow removed?


I am confused about the following behaviour of Julia when using array comprehensions that have arrays/matrices in them. They seemingly seem to bury the other dimensions of the inside array. I am looking to get an array of dimension 2,4,3 in the end.

myarr = Array{Float64}(undef,4,3)
broken_off_dim = [myarr for i in 1:2]
size(broken_off_dim)

Somehow, I get (2,) and I wonder what happened to the inner dimensions? Can you help modify the above code so that (2,4,3) comes out? I tried reshaping but that throws an error.

Functions that are applied over a specific margin also do not work properly then.


Solution

  • If you want a comprehension to make one array rather than an array of arrays, then you probably want stack.

    julia> vv = [[i, 2i, 3i] for i in 1:4]
    4-element Vector{Vector{Int64}}:
     [1, 2, 3]
     [2, 4, 6]
     [3, 6, 9]
     [4, 8, 12]
    
    julia> mat = stack(vv)  # inner dimension(s) go first
    3×4 Matrix{Int64}:
     1  2  3   4
     2  4  6   8
     3  6  9  12
    
    julia> mat == stack([i, 2i, 3i] for i in 1:4)
    true
    
    julia> mat == stack((i, 2i, 3i) for i in 1:4)
    true
    

    Notice that it accepts an un-collected comprehension generator too, without making the Vector{Vector{T}} first. In fact almost any iterator of iterators.

    With more dimensions, all dimensions are preserved. (I think the example above probably wants stack(myarr(i) for i in 1:2; dims=1).)

    julia> vm = [[i 10i; 2i 21i] for i in 1:4]
    4-element Vector{Matrix{Int64}}:
     [1 10; 2 21]
     [2 20; 4 42]
     [3 30; 6 63]
     [4 40; 8 84]
    
    julia> vm[end]
    2×2 Matrix{Int64}:
     4  40
     8  84
    
    julia> stack(vm) |> summary
    "2×2×4 Array{Int64, 3}"
    
    julia> stack(vm; dims=2) |> summary
    "2×4×2 Array{Int64, 3}"
    

    On Julia 1.8 or earlier, you will need using Compat for this.