Indexing into multidimensional array for general n dimensions

Hi,

Let’s consider an array X of two dimensions, here X[1,1] is of type Array{Float64, 2}, i.e. n = 2:

julia> X
2×2 Array{Array{Float64,2},2}:
 [0.0 0.0; 0.0 0.0; 0.0 0.0]  [2.0 2.0; 2.0 2.0; 2.0 2.0]
 [2.0 2.0; 2.0 2.0; 2.0 2.0]  [2.0 2.0; 2.0 2.0; 2.0 2.0]

I obtain y from X by doing:

julia> [y[i,j,:,:] = X[i,j] for i in 1:size(X, 1) for j in 1:size(X, 2)]

Now for the general case when X[1][1] is of type Array{Float64, n} where n ∈ ℕ, what can I do to get y for general n in similar way?

pseudo-code would be:

julia> [y[i,j,:,:,:,:,:,.....] = X[i,j] for i in 1:size(X, 1) for j in 1:size(X, 2)]

Maybe you want GitHub - ChrisRackauckas/EllipsisNotation.jl: Implements the notation `..` for indexing arrays.. And more generally GitHub - mcabbott/LazyStack.jl: 🥞 or one of the packages mentioned there.

2 Likes

Are you sure this is how you want the data organized? You are taking data that are originally sequentially located in memory and scattering them far from each other (this is the opposite of what would happen Python, btw, where the above pattern is optimal). If you want to keep them sequential in memory, it makes more sense to do

julia> [y[:,:, i, j] = X[i,j] for i in axes(X, 1) for j in axes(X, 2)]

(using axes is a bit more robust than 1:length)

3 Likes