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?
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.
You could also use cat
if you don’t need a mutating version.
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
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).
The thing you are adding needs to have the same dimension as the thing you are appending to:
2-dimensional array
A = [[1, 1]]
append a 2-d array to A
append!(A, [[2, 2]])
I think you misunderstand something: [[1, 1]]
is a Vector
(one-dimensional array), with another Vector
for elements. This is not equivalent to 2-dimensional arrays.
Also, please don’t revive old topics without a compelling reason.
A
is an array of array. Not a two dimensional array.