# Indexed variable names, or vector of vectors?

I have to update values of a number of vectors, say s1 … s20. I need a way to access arbitrarily s_n, the nth index of variable s.

s1=[1 2 3]
s2=[11 12 13 14 15]

# calculations lead to "n" and "val"
n=2
val=16

# I append "val" to the "n"th variable "s".
if n == 1
append!(s1, val)
elseif n == 2
append!(s2, val)
# elseif ... same for n=3, n=4 ...
end

I would like to reduce code duplication. I found on this forum : How to change the name of a variable in a for loop So I rewrote as:

@eval append!(\$(Symbol(:s,n)),value)

It works, but it is 10x slower (I have a loop over millions of data points).

I was previously working with scilab. The same program as above can be done in scilab by defining variable s as a list, in which the elements of any type can be indexed.

// Scilab 6.1.1 console
s=list()
s(1)=[1 2 3]
s(2)=[11 12 13 14 15]
// ... we can append to s by calling s(\$+1), for example in a loop

n=2
val=16

// we call the "n"th index of list "s" and append "val" in the end
s(n)(\$+1)=val

Is it possible to do something similar in julia? I mean defining a heterogeneous list or a vector of vectors where each of the elements can grow dynamically? (without compromising too much of execution performance)

yes

julia> s = [Int[] for _ = 1:20]; #vector of vector

julia> append!(s[3], 20);

julia> s[2]
Int64[]

julia> s[3]
1-element Vector{Int64}:
20

or you can use a Dict() with Int as keys and Vector{Int} as values

2 Likes