Convert Matrix{Vector{Float64}} -> Array{Float64, 3}?

I have a matrix of vectors, the indices of the matrix serve as (row, column) and the Vector is the z coordinate. Is there some way to convert this?

I read data from disk in as Array{Float64, 3} and then try to do a cumulative trapezoidal integration on it like this:

Example code generating the data I need converted:

function cumtrapz(x::AbstractVector, y::AbstractVector)
    @assert length(x) == length(y)
    N = length(x)
    g = similar(y)
    g[1] = zero(eltype(y))

    for k = 1:N - 1
        g[k + 1] = g[k] + (x[k + 1] - x[k]) * (y[k + 1] + y[k]) / 2
    end

    return g
end

function integrate_data(x, y)
    xx = eachslice(x, dims=(1, 2))
    yy = eachslice(y, dims=(1, 2))
    copd = cumtrapz.(xx, yy)
end

# Junk data, representing real data.
U = Array{Float64, 3}(reshape(1:27, (3, 3, 3)))
V = sqrt.(U)
cumulative_v = integrate_data(U, V)
# typeof(cumulative_v) is Matrix{Vector{Float64}} ... and I need it to be Array{Float64, 3}

Check out the function called stack

1 Like

I’m not sure how it can be used for this?

Thanks, I think in my particular case the answer would be:

permutedims(stack(cumulative_v), (2, 3, 1))

I need the numbers to get bigger with each z slice … thus, permutedims.

2 Likes

EDIT: the above beat me to this.

Try

julia> A = [[100i+10j+1;100i+10j+2] for i in 1:3, j in 1:4]
3×4 Matrix{Vector{Int64}}:
 [111, 112]  [121, 122]  [131, 132]  [141, 142]
 [211, 212]  [221, 222]  [231, 232]  [241, 242]
 [311, 312]  [321, 322]  [331, 332]  [341, 342]

julia> permutedims(stack(A),(2,3,1))
3×4×2 Array{Int64, 3}:
[:, :, 1] =
 111  121  131  141
 211  221  231  241
 311  321  331  341

[:, :, 2] =
 112  122  132  142
 212  222  232  242
 312  322  332  342

permutedims (or PermutedDimsArray) is necessary because you want to have the vectors splayed along the final dimension, rather than first. Alternatively, you could write few loops to do the whole concatenation. It wouldn’t be intrinsically slower than using these built-ins.

1 Like

Ha! mere seconds after I figured it out.
I know and have tested that loops are not a bad thing, but so many years of Matlab and Python have me thinking that loops are bad, hard to get out of the desire to not use them.

1 Like