Convert 2×2 Array{Array{Float64,1},2} into Array{Float64, 3}

Dear all,

How do I convert an object of type Array{Array{Float64,1},2} to an object of type Array{Float64, 2}?

For ex.

> t = Array{Array{Float64,1}, 2}(undef, (2, 2))
> t[1] = [0., 0, 0];
> t[2] = [0., 0, 0];
> t[3] = [2., 2, 2];
> t[4] = [2., 2, 2];
> t
2×2 Array{Array{Float64,1},2}:
 [0.0, 0.0, 0.0]  [2.0, 2.0, 2.0]
 [0.0, 0.0, 0.0]  [2.0, 2.0, 2.0]

> t2 = Array{Float64, 3}(undef, 2, 2, 3)
> t2[1,1,1] = 0.
> t2[1,1,2] = 0.
> t2[1,1,3] = 0.
> t2[2,1,1] = 0.
> t2[2,1,2] = 0.
> t2[2,1,3] = 0.
> t2[1,2,1] = 2.
> t2[1,2,2] = 2.
> t2[1,2,3] = 2.
> t2[2,2,1] = 2.
> t2[2,2,2] = 2.
> t2[2,2,3] = 2.;
t2

2×2×3 Array{Float64,3}:
[:, :, 1] =
 0.0  2.0
 0.0  2.0

[:, :, 2] =
 0.0  2.0
 0.0  2.0

[:, :, 3] =
 0.0  2.0
 0.0  2.0

The steps to convert t to t2.

Unfortunately, I cannot copy and paste any code to reproduce your input, but you may try reduce(hcat, X) followed by an appropriate reshape

2 Likes

I can do that, but the thing the ordering of values is not what I expect. Using reshape(reduce(hcat, X), (2, 2, 3)) I get:

2×2×3 Array{Float64,3}:
[:, :, 1] =
 0.0  0.0
 0.0  0.0

[:, :, 2] =
 0.0  2.0
 0.0  2.0

[:, :, 3] =
 2.0  2.0
 2.0  2.0

which isn’t the expected outcome.

Transpose the result of reduce(hcat, X) and you’ll have it it:

julia> reduce(hcat, X) |>
       a -> permutedims(a, (2,1)) |>
       a -> reshape(a, (2,2,3))
2×2×3 Array{Float64,3}:
[:, :, 1] =
 0.0  2.0
 0.0  2.0

[:, :, 2] =
 0.0  2.0
 0.0  2.0

[:, :, 3] =
 0.0  2.0
 0.0  2.0
3 Likes