# Stack with new axis last

**URL:** <https://discourse.julialang.org/t/stack-with-new-axis-last/119090>\
**Category:** General Usage\
**Tags:** arrays\
**Created:** [September 5, 2024, 9:47pm UTC](https://discourse.julialang.org/t/stack-with-new-axis-last/119090 "2024-09-05T21:47:06Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jar1](https://avatars.discourse-cdn.com/v4/letter/j/c0e974/32.png) [@jar1](https://discourse.julialang.org/u/jar1)\
**Post date:** [September 5, 2024, 9:47pm UTC](https://discourse.julialang.org/t/stack-with-new-axis-last/119090/1 "2024-09-05T21:47:06Z")

</div>

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
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'

```

---

<div class="post-metadata">

**Author:** ![mcabbott](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mcabbott/32/6603_2.png) [@mcabbott](https://discourse.julialang.org/u/mcabbott)\
**Post date:** [September 6, 2024, 1:16am UTC](https://discourse.julialang.org/t/stack-with-new-axis-last/119090/2 "2024-09-06T01:16:11Z")

</div>

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

```julia
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)`.

---

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [September 7, 2024, 2:45pm UTC](https://discourse.julialang.org/t/stack-with-new-axis-last/119090/3 "2024-09-07T14:45:05Z")

</div>

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

Thanks.

NB:  
[This post](https://discourse.julialang.org/t/memory-allocation-when-using-permutedims/105806/2) answers the question.
