在 Julia 中迭代数组

Sti*_*ine 4 julia

这是我想使用的功能。我正在尝试使用整周的温度数据和降水数据。这意味着参数:temp& precip,将是一个长度为 7 的数组。我如何使其工作?

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  
Run Code Online (Sandbox Code Playgroud)

该函数的结果如下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
Run Code Online (Sandbox Code Playgroud)

fre*_*kre 7

问题在于您如何创建迭代空间:for i in 1:size(precip)size在 Julia 中返回一个元组。您想length改用(或size(precip, 1)用于第一维中的大小)。

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  
Run Code Online (Sandbox Code Playgroud)


Fre*_*gge 6

第一个 Fredrik 给出的答案就是你的问题的答案。这只是计算同一事物的一种简短而有效的方法。

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 
Run Code Online (Sandbox Code Playgroud)

注意,元组解构moist_effect((i,x)),我说这个,因为enumerate指数和值的迭代元组。

该函数sum有一个方法,它接受一个函数作为它的第一个参数。此方法在对所有元素求和之前将该函数应用于所有元素。