in my code I often use function broadcasting and then end up with objects A like T-element Vector{m-element Vector{Float64}}. I was wondering if there is an easy command to convert A into T-by-m or m-by-T matrix.
It’s not hard to find a work-around by creating an empty T-by-m matrix B and then looping through the ‘vector’ A and assigning each row of B an element
B = zeros(T,m)
for t in 1:T
B[t,:] = A[t]
end
but I was still wondering if there is faster/less wordy way to do this.
The question is also, why do you end up with a nested array in the first place?
From the top of my head, I could think of two obvious ways
You are using eachslice or something like that
You broadcast a function returning an array
In such cases, there are several libraries like SplitApplyCombine.jl or JuliennedArrays.jl which can split into and recombine from nested arrays, i.e., just like stack already mentioned. Further, I had experimented with a small library JJ.jl which allows to apply functions to smaller dimensional parts of an array and automatically recollects all results into an array:
julia> A = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
1 2 3
4 5 6
julia> foo(x) = x .+ [-1, 1]
foo (generic function with 1 method)
julia> foo.(A)
2×3 Matrix{Vector{Int64}}:
[0, 2] [1, 3] [2, 4]
[3, 5] [4, 6] [5, 7]
julia> using JJ
julia> rank"foo 0"(A) # Same as stack(foo.(A))
2×2×3 Align{Int64, 3} with eltype Int64:
[:, :, 1] =
0 3
2 5
[:, :, 2] =
1 4
3 6
[:, :, 3] =
2 5
4 7
julia> rank"foo 1"(A) # same as stack(foo.(eachslice(A; dims=2)))
2×3 Align{Int64, 2} with eltype Int64:
0 1 2
5 6 7