# Stack arrays into array with extra dimension

**URL:** <https://discourse.julialang.org/t/stack-arrays-into-array-with-extra-dimension/8470>\
**Category:** General Usage\
**Tags:** question\
**Created:** [January 19, 2018, 11:39am UTC](https://discourse.julialang.org/t/stack-arrays-into-array-with-extra-dimension/8470 "2018-01-19T11:39:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [January 19, 2018, 11:39am UTC](https://discourse.julialang.org/t/stack-arrays-into-array-with-extra-dimension/8470/1 "2018-01-19T11:39:48Z")

</div>

This pattern comes up often for me (eg analyizing simulations, posterior predictive checks). I have a solution, but I wonder if there is a better one. MWE:

```julia
"""
Collect arrays in the argument such that

`stack1(v)[1, fill(:, ndims(v[i]))...] == v[i]`
"""
stack1(v) = reshape(transpose(hcat(map(vec, v)...)), :, size(first(v))...)

g = (reshape((1:6)*i, 2, 3) for i in 1:10);
s = stack1(g);

```

so that

```julia
julia> s[1, :, :]
2×3 Array{Int64,2}:
 1 3 5
 2 4 6

julia> s[2, :, :]
2×3 Array{Int64,2}:
 2 6 10
 4 8 12

```

I do things like `stack1(map(f, as, bs))` where `as` and `bs` are different and `mapslices` would not work.

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [January 19, 2018, 12:29pm UTC](https://discourse.julialang.org/t/stack-arrays-into-array-with-extra-dimension/8470/2 "2018-01-19T12:29:18Z")

</div>

```julia
julia> g = (reshape((1:6)*i, 1, 2, 3) for i in 1:10);

julia> s = cat(1, g...);

julia> s[1,:,:]
2×3 Array{Int64,2}:
 1 3 5
 2 4 6

julia> s[2,:,:]
2×3 Array{Int64,2}:
 2 6 10
 4 8 12

```
