How to convert Vector of Vectors to Matrix

Right?! This would make so much sense! A vector of equal-size vectors is a matrix! Julia even displays vectors of vectors neatly by rows (well, all vectors are displayed by rows, but this looks a lot like a matrix):

julia> sol.u
1001-element Vector{Vector{Float64}}:
 [1.0, 0.0, 0.0]
 [1.2714553023510824, 2.5502478518250142, 0.1141384466168722]
 [3.9131447607344776, 8.433083437324328, 1.2683805363770986]
 [11.696231301993413, 22.993582131160995, 11.769786900084997]
 [19.698658008680177, 16.751621637382875, 45.82588214497926]
 [6.503654894191205, -8.508354690536336, 38.091997347142616]
 [-3.332076962123722, -8.698838751487166, 28.734916780144353]
 [-6.535890901038596, -8.425700745706362, 25.905899192608068]
...

Matrix(sol.u) is easy to read and easy to write: want to convert stuff to a matrix? - use the Matrix constructor!

But no, here we have 25 comments and a bunch of complex solutions:

  • mapreduce(permutedims, vcat, x) is complex because, arguably, mapreduce is an advanced concept from functional programming, big data and Apache Hadoop. This also requires knowing what mapreduce, permutedims and vcat do - all this for converting a vector of vectors into a matrix? IMO, it’s way too general.

  • permutedims(hcat(x...)) is complex because I need to know what permutedims and hcat do to use this. I also need to splat my potentially huge vector x and thus pass a million arguments to hcat. Indeed, “don’t use splatting of large arrays”.

    Yep, it’s not immediately clear what this code does. Matrix(x) won’t leave people wondering what’s going on.

  • reduce(vcat,transpose.(x)) again requires me to know three unrelated functions. Okay, transpose is simple because it does what its name says. But it’s not immediately clear that this incantation builds a matrix from a vector of vectors. Why write this convoluted code instead of Matrix(vec_of_vecs)??

  • reduce(hcat,x)' is basically the same as the previous point.

  • IMO, this is the most straightforward code in this thread. However, shouldn’t this be part of the standard library?

  • I find it disturbing that I can install a package to cleanly convert a vector of vectors to a matrix. It could simply be one of Matrix’s constructors.

3 Likes