Create a row matrix of vectors

I’d like to be able to create a row matrix holding vectors (the purpose is to pass them as series to Plots, but the question is general). However, I get issues with concatenation. I can create a vector of different-length vectors easily: a = [rand(n) for n in 2:5] but a' fails with an error relating to concatenating different length vectors. It does seem possible to create a 2-d array of arrays:

test = Matrix{Any}(5,5)
fill!(test, rand(5))

works, but only as long as the arrays all have the same length. Am I abusing the syntax?

Silly me, I can just use reshape. Sorry

Could you provide an example of what you wanted and your solution? This might be useful for me and others.

Thanks!

You can skip the reshape (or transpose) call by using multi-dimensional comprehension syntax:

julia> [rand(n) for i=1:1, n=1:3]
1×3 Array{Array{Float64,1},2}:
  [0.19346]  [0.875024,0.573032]  [0.26811,0.288699,0.481266]

Note that just using i=1 still only produces a 1-D vector since as a scalar it’s making a contribution of 0 to the overall result dimension.

Also, note that using fill! is probably wrong here because it’s only allocating and building a single vector of numbers and putting a reference to that same vector object in each place in the matrix.

1 Like
reshape(v,1,length(v))

should reshape a column vector to a row vector. Since reshape is a view it should be pretty cost-free too.

One place this comes up is when working with Plots.jl. A series is usually a column, and so rows denote the different series. So giving something like a labels for legends needs to be a row vector. I used to just transpose the vector of names (strings) I’d get in my recipes, but that’s being deprecated. The reshape trick works just fine though.

3 Likes

Thanks, Chris, was late to respond.