【问题标题】:Iterate over arrays in Julia迭代 Julia 中的数组
【发布时间】:2020-05-20 12:41:06
【问题描述】:

这是我要使用的功能。我正在尝试使用一整周的温度数据和降水数据。这意味着参数: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

【问题讨论】:

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

标签: julia


【解决方案1】:

问题在于如何创建迭代空间: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  

【讨论】:

  • eachindex(temp, precip),而不是整个范围。
  • 是的,这也确保了两个数组的长度匹配。
【解决方案2】:

第一个 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 有一个接受函数作为其第一个参数的方法。此方法在汇总之前将该函数应用于所有元素。

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 2017-04-24
    • 1970-01-01
    • 2017-07-31
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多