Reputation: 95
This is the function I want to use. I am trying to use temperature data & precipiation data of a whole week. This means the arguments: temp
& precip
, will be an array of length 7. How do i make this work?
function humidityindex(temp, precip)
moist_effect = 0
temp_effect = 0
for i in 1:size(precip)
moist_effect += ((precip[i]/100) * (1-(i/10)))
temp_effect -= ((temp[i]/25) * (1-(i/10)))
end
effect = temp_effect + moist_effect
return effect
end
The function results in the following MethodError
:
julia> t = rand(7); p = rand(7);
julia> humidityindex(t, p)
ERROR: MethodError: no method matching (::Colon)(::Int64, ::Tuple{Int64})
Closest candidates are:
Any(::T, ::Any, ::T) where T<:Real at range.jl:41
Any(::A, ::Any, ::C) where {A<:Real, C<:Real} at range.jl:10
Any(::T, ::Any, ::T) where T at range.jl:40
...
Stacktrace:
[1] humidityindex(::Array{Float64,1}, ::Array{Float64,1}) at ./REPL[1]:4
[2] top-level scope at REPL[3]:1
Upvotes: 5
Views: 2347
Reputation: 1381
The answer given by the first Fredrik is the answer to your question. This is simply a short and efficient way of calculating the same thing.
moist_effect((i,x)) = (x/100) * (1-(i/10))
temp_effect((i,x)) = -(x/25) * (1-(i/10))
function humidityindex(temp, precip)
sum(moist_effect, enumerate(precip)) + sum(temp_effect, enumerate(temp))
end
Notice the tuple destructuring in moist_effect((i,x))
, I added this since enumerate
iterates tuples of indices and values.
The function sum
has a method that accepts a function as its first argument. This method applies that function to all elements before summing them up.
Upvotes: 6
Reputation: 10984
The problem is how you create the iteration space: for i in 1:size(precip)
. size
in Julia returns a tuple. You want to use length
instead (or size(precip, 1)
for the size in the first dimension).
function humidityindex(temp, precip)
moist_effect = 0
temp_effect = 0
for i in 1:length(precip) # <-- Updated this line
moist_effect += ((precip[i]/100) * (1-(i/10)))
temp_effect -= ((temp[i]/25) * (1-(i/10)))
end
effect = temp_effect + moist_effect
return effect
end
Upvotes: 7