# Stack with new axis last

This makes a `5×2×3` array. If I want instead a `2×3×5` array, can I do it by passing `;dims=` or do I need to `permutedims` afterwards?

``````julia> a = map(collect∘join, (Iterators.product((["AB", "CD"], ["rst", "uvw", "xyz"])...)))
2×3 Matrix{Vector{Char}}:
['A', 'B', 'r', 's', 't']  ['A', 'B', 'u', 'v', 'w']  ['A', 'B', 'x', 'y', 'z']
['C', 'D', 'r', 's', 't']  ['C', 'D', 'u', 'v', 'w']  ['C', 'D', 'x', 'y', 'z']

julia> stack(a)
5×2×3 Array{Char, 3}:
[:, :, 1] =
'A'  'C'
'B'  'D'
'r'  'r'
's'  's'
't'  't'

[:, :, 2] =
'A'  'C'
'B'  'D'
'u'  'u'
'v'  'v'
'w'  'w'

[:, :, 3] =
'A'  'C'
'B'  'D'
'x'  'x'
'y'  'y'
'z'  'z'
``````

You can use `stack(a; dims=1)` and then `reshape` for this, or a comprehension:

``````julia> c = stack(a; dims=1); summary(c)  # outer axes combined to 1st, like vec(a)
"6×5 Matrix{Char}"

julia> d = reshape(c, size(a)..., :); summary(d)
"2×3×5 Array{Char, 3}"

julia> d[1,1,:] == a[1,1]
true

julia> e = [a[i,j][k] for i in axes(a,1), j in axes(a,2), k in axes(a[1],1)];

julia> e == d
true
``````

This operation would be `stack(a; dims=(1,2))` if that existed. But right now, keeping multiple outer axes only works when they are last, as in `stack(a)`.

2 Likes

@mcabbott, what are the advantages of your proposed solution over OP’s original idea of using: `permutedims(stack(a),(2,3,1)) ` ?

Thanks.

NB: