Array of Vectors with Different Lengths

I am trying to create a data structure that can hold vectors that have different lengths, and I don’t know how many vectors I will have to store. I have been struggling with coming up with a method that can accomplish this. I have developed the following code to accomplish this:

function TestFunction(PreVec)
    for i=1:5
        Number = rand(1:10)
        NewVec = rand(1:10,Number,1 )
        Combined = [PreVec, NewVec]
        PreVec = Combined
NumberInit = rand(1:10)
PreVec = rand(1:10,NumberInit,1 )

The issue with the above method is that I want my code to generate an array that has a length equivalent to the number of vectors that have been stored in the array. What the code above produces however is a nested array so that it is always of size 2. How could I modify the code above or use a different method to avoid this issue that I have of the nested arrays?

Use push! to add each new vector to a vector of vectors.

1 Like

You probably just want to push! your new vector onto the vector of vectors:

ragged_array = []
push!(ragged_array, rand(4))
push!(ragged_array, rand(2))
# etc

PS: this takes me way back, my first “public” Julia-code had some ragged array stuff in it: maurow / LMesh.jl / commit / d67401b22e44 — Bitbucket