Reputation: 307
In the julia code below, the first entry of a_b will be updated in a for-loop. However, I want it to always stay an integer regardless of what it gets updated to, because I get the error: "ERROR: LoadError: ArgumentError: invalid index: 7.0 of type Float64" when I do the final line of my code as it is currently written below (the 7.0 is because ultimately the j in which we terminally assign a_b[1] to is indeed 7.0).
How does one accomplish this? Is there a way to preset the types for the entries in an array analogous to how one can set types when you define a dictionary in julia?
a_b = [0, 1.0]
for j in 1 : 7
if T_w[j] > a_w_comma_T_w[2] && T_w[j] < a_b[2]
a_b[1] = j
a_b[2] = T_w[j]
end
end
println("This is a_b: ", a_b)
T_prime = copy(T_w)
T_prime[a_b[1]] = a_w_comma_T_w[2]
I think the problem is that the second entry in the array is a float (which I want to keep), and so it makes the whole array a float. However, I'm still not sure how to fix it.
Upvotes: 4
Views: 420
Reputation: 42194
You can narrow the element type when defining the Vector
using the T[]
syntax such as:
julia> a_b = Int[0, 1.0]
2-element Vector{Int64}:
0
1
Now you have a Vector
of Int
s and mutating it will keep Int
values:
julia> a_b[1] = 77.0
77.0
julia> a_b
2-element Vector{Int64}:
77
1
Of course, rounding will not happen automatically:
julia> a_b[1] = 77.1
ERROR: InexactError: Int64(77.1)
Upvotes: 1
Reputation: 4510
For each element to have a separate type but also be mutable, you'll need something other than an Array. Don't have something off the type of my head that is indexed by integers, though. I normally go for mutable structs (accessed by fields) or separate variables that I keep independently type-stable.
You could do a_b = Union{Int, Float64}[0, 1.0]
, though. Each element can be either an Int or a Float64 instead of being converted to only a Float64. And since the Union is small, the Union-splitting optimization results in little performance loss.
Upvotes: 1