Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over arrays in Julia

Tags:

julia

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
like image 600
Stijn_antoine Avatar asked Dec 10 '22 00:12

Stijn_antoine


1 Answers

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  
like image 161
fredrikekre Avatar answered Dec 12 '22 12:12

fredrikekre