Appending to a multidimensional array


#1

So I am generating a sequence of Nxd arrays, which are trajectories in d-diemsnional space. I would like to append them to one another. In the case d=1, I can do this with append! Is there a generalization to the d-dimensional case?


#2

As far as I know, there is no way to append to a multidimensional array. However, you can maintain the array as an N*d 1-dimensional array, append to this, and then use reshape to see it in the shape that you want. The reshape function does not actually move or copy the data but instead provides a different view into it, so this technique is reasonably efficient.


#3

You could also use cat if you don’t need a mutating version.


#4

Check out tho documentation of cat you can specify the dimension along which you want to concatenate N-dimensional arrays:

1D:

julia> append!([1, 2, 3], [4, 5, 6])        # mutating!
6-element Array{Int64,1}:                   
 1                                          
 2                                          
 3                                          
 4                                          
 5                                          
 6                                          
                                            
julia> cat(1, [1, 2, 3], [4, 5, 6])         
6-element Array{Int64,1}:                   
 1                                          
 2                                          
 3                                          
 4                                          
 5                                          
 6      

Generalization:

julia> cat(2, [1, 2, 3], [4, 5, 6])         
3×2 Array{Int64,2}:                         
 1  4                                       
 2  5                                       
 3  6                                       
                                            
julia> cat(3, [1 2 ;3 4], [5 6 ; 7 8])      
2×2×2 Array{Int64,3}:                       
[:, :, 1] =                                 
 1  2                                       
 3  4                                       
                                            
[:, :, 2] =                                 
 5  6                                       
 7  8                                       

#5

Check out https://github.com/JuliaArrays/ElasticArrays.jl.

Also consider using Vector{SVector{d, Float_T}} if you can live with d being a jit-time constant (this could actually speed up your code because it allows specialization on d).