Reputation: 33
Consider an array of arrays
julia> a
2-element Array{Array{Float64,1},1}:
[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
I want to convert a into an Array{Float64,2}
2×3 Array{Float64,2}:
1.0 2.0 3.0
4.0 5.0 6.0
like so.
I found out that one solution hcat(a...)'
julia> hcat(a...)'
2×3 Adjoint{Float64,Array{Float64,2}}:
1.0 2.0 3.0
4.0 5.0 6.0
Here type is Adjoint{Float64,Array{Float64,2}}. But for my problem, I need only Array{Float64,2}. And after some computations, I need to convert it back into array of arrays. I am wondering, what should be the best way to do this.
Thanks in advance.
Upvotes: 3
Views: 366
Reputation: 69949
You can do:
julia> reduce(vcat, transpose.(a))
2×3 Array{Float64,2}:
1.0 2.0 3.0
4.0 5.0 6.0
or e.g. (this does not check if the dimensions of the vectors match)
julia> [v[i] for v in a, i in axes(a[1], 1)]
2×3 Array{Float64,2}:
1.0 2.0 3.0
4.0 5.0 6.0
the way back is simpler:
julia> b = reduce(vcat, transpose.(a))
2×3 Array{Float64,2}:
1.0 2.0 3.0
4.0 5.0 6.0
julia> copy.(eachrow(b))
2-element Array{Array{Float64,1},1}:
[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
or
julia> [b[i, :] for i in axes(b, 1)]
2-element Array{Array{Float64,1},1}:
[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
Upvotes: 3