Converting a matrix into an array of arrays

question

#1

Hi all

I have seen many examples of converting an array of arrays into a matrix, but I would like to go the other way. What I have cobbled together works, but may not be the most elegant or fast solution. I would appreciate any comments and builds.

function sliceMatrix(A)
    m, n = size(A)
    B = Array{Array{eltype(A), 1}, 1}(undef, m)

    for i = 1:m
        B[i] = A[i, :]
    end
    return B
end

Is there a way to pre-allocate the individual arrays inside B?

Thanks!


#2

I don’t think you gain much from preallocating in this situation, but here is one way where I only modified your functions a little bit:

julia> function slicematrix(A::AbstractMatrix{T}) where T
           m, n = size(A)
           B = Vector{T}[Vector{T}(undef, n) for _ in 1:m]
           for i in 1:m
               B[i] .= A[i, :]
           end
           return B
       end
slicematrix (generic function with 1 method)

julia> slicematrix(rand(2,3))
2-element Array{Array{Float64,1},1}:
 [0.686489, 0.016934, 0.638272]
 [0.317802, 0.543907, 0.208549]

but it is probably better and simpler to just define it as:

function slicematrix(A::AbstractMatrix)
    return [A[i, :] for i in 1:size(A,1)]
end

Note also that Julia’s Array is column major, so extracting columns (A[:, i]) is much faster than extracting rows (A[i, :]).


#3

A one liner, likely not as efficient as the suggestion above, is
mapslices(x->[x], randn(5,5), dims=2)[:]


#4

Thank you all! The suggestions are much appreciated.