I’m sure there are more elegant solutions, but here is one that works:
using Random
Random.seed!(5411)
function pivot_longer(x)
output = zeros(length(x), length(size(x))+1)
for (i,idx) in enumerate(CartesianIndices(x))
output[i,:] = [idx.I... x[idx]]
end
return output
end
x = rand(2, 2, 2)
y = pivot_longer(x)
output
julia> x
2×2×2 Array{Float64, 3}:
[:, :, 1] =
0.93722 0.283684
0.988042 0.183431
[:, :, 2] =
0.970431 0.842597
0.473857 0.121432
julia> y
8×4 Matrix{Float64}:
1.0 1.0 1.0 0.93722
2.0 1.0 1.0 0.988042
1.0 2.0 1.0 0.283684
2.0 2.0 1.0 0.183431
1.0 1.0 2.0 0.970431
2.0 1.0 2.0 0.473857
1.0 2.0 2.0 0.842597
2.0 2.0 2.0 0.121432