I am trying to understand the difference between the two ways I found to create a vector of vectors below. I found Option 1 in this post, which works nicely but isn’t very customizable. Option 2 also works, but it can’t seem to obtain the type. Why aren’t the types the same between Option 1 and 2, and what does “where T,1” mean? How can I fix Option 2’s typing, so that I don’t take a performance hit?
Bonus Question: My understanding is that tuples are faster than vectors because they are immutable. How can I construct a tuple of vectors and then fill the vectors in a loop? Neither replacing []
with ()
in Option 1 nor Vector
with Tuple
in Option 2 worked. I see in my testing that I may modify the interior vectors v[j][i]=
, but not the tuples indices themselves v[j]=
once created. However, I can’t figure out how to set up this structure if I don’t know the values in the vectors at creation time. How can I achieve this and is the performance gain worth the hassle?
#Vector Lengths
J=4
I=11
#Creation Option 1
v=[Vector{Int}(undef, I) for _ = 1:J]
#Creation Option 2
v=Vector{Vector}(undef, J) # Outer Vector (May in practice want outer type to be a tuple.)
for j in 1:J
v[j]=Vector{Int}(undef, I) # Inner Vector (May in practice have different lengths.)
end
#Fill with test values.
for j=1:J
for i=1:I
v[j][i]=(j-1)*I+i
end
end
#Show Results
v
Output of Option 1:
4-element Array{Array{Int64,1},1}:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
[23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
[34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]
Output of Option 2:
4-element Array{Array{T,1} where T,1}:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
[23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
[34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]