Create a vector accepting different datatypes at specific index positions

Hi all,

I’m wondering how to initialize a vector that requires different datatypes at specific positions. I want the first element in the array to be of type Int64, and the second element in the array to be of type Float64. The below example code is making both array elements Float64, which I don’t want:

arr = Vector{Vector{Union{Int64, Float64}}}()

r_arr = [2.0, 4.0, 6.0] 

for ii in 1:4
  for jj in r_arr
    push!(arr, [ii, jj])
  end 
end 

Undesirable output below:
image

How can I modify my code to force the first element of the vector to be an Int64 and the second element of the vector to be a Float64? Can this be done with vector’s, or will I need to use another data type (e.g. Array)?

Thanks.

Are you sure you don’t want a Vector{Tuple{Int64, Float64}}

1 Like

That one works, cheers.

Is there a way to use a Vector or Array instead of Tuple in this case? I like the mutability of Vectors and Arrays compared to Tuples immutability, but I shouldn’t need to change the Int64 and Float64 values so it ultimately shouldn’t matter much.

You could always make a mutable struct that stores an Int and Float64. In general, figuring out a data-structure that naturally represents your data is a good idea.

2 Likes