在Julia中迭代数组

5

这是我想要使用的函数。我尝试使用整个星期的温度数据和降水数据。这意味着参数:tempprecip将是长度为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  

该函数结果会导致以下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

1
你能解释一下你的问题具体是什么吗?乍一看,代码似乎没有任何问题,但当然这取决于tempprecip的定义方式。你能把它们添加到你的示例中,并展示函数的输出与你期望的有何不同吗? - Nils Gudat
感谢您的编辑 - 这正是Fredrik在下面预期的问题(size()返回一个维度元组,因此您正在尝试创建范围1:(7,)而不是范围1:7)。 - Nils Gudat
2个回答

7
问题在于如何创建迭代空间:for i in 1:size(precip)。 在Julia中,size会返回一个元组。您应该使用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  

1
或者使用 eachindex(temp, precip) 而不是整个范围。 - phipsgabler
是的,这也确保了两个数组的长度匹配。 - fredrikekre

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 

注意在moist_effect((i,x))中的元组解构,我加入了这个操作,因为enumerate遍历的是索引和值的元组。

sum函数有一个方法可以接受一个函数作为其第一个参数。此方法将该函数应用于所有元素,然后将它们求和。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接