Convert a Vector of Vectors to an Array

It’s often the case in physics that one deals with a vector (i.e. a 1d array or list), where each entry is also a vector. Here’s some code which takes a list of vectors and converts them into an array in Julia.

The code is also available in a public gist at

Here is the code (tested in Julia 1.8.5)

# Convert a vector of vectors to an array
This function assumes that each vector is the same length;
v1 = [ [1,2], [2,3], [5,6] ] # this is fine
v2 = [ [1,2,8], [2,3], [5,6] ] # this is not fine

Example of usage:
vv = [[1,2,3], [4,5,6], [7,8,9],[12,13,14]]
println("num components in each vector = ", length(vv[1]))
println("num of vectors = ", length(vv))
function vecvec_to_array(vecvec)
    dim1 = length(vecvec)
    dim2 = length(vecvec[1])
    my_array = zeros(Int64, dim1, dim2)
    for i in 1:dim1
        for j in 1:dim2
            my_array[i,j] = vecvec[i][j]
    return my_array

About PaulNakroshis

Professor of Physics at the University of Southern Maine.
This entry was posted in Array, Julia. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.