在Julia中迭代数组

在Julia中迭代数组,julia,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
&
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  
该函数导致以下
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
julia>t=rand(7);p=兰特(7);
julia>湿度指数(t,p)
错误:MethodError:没有方法匹配(::冒号)(::Int64,::Tuple{Int64})
最接近的候选人是:

Any(::T,::Any,::T)其中T问题是如何为i在1:size(precip)中创建迭代空间:
size
返回一个元组。您希望改为使用
length
(或者
size(precip,1)
作为第一个维度中的大小)

功能湿度指数(温度、精度)
湿润效应=0
温度效应=0

对于1:length(precip)#中的i,第一个弗雷德里克给出的答案就是你问题的答案。这是一种简单而有效的计算同一事物的方法

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 
注意
湿润效应((i,x))
中的元组分解,我添加了这一点,因为
枚举
迭代索引和值的元组


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

你能解释一下你的问题到底是什么吗?乍一看,代码似乎没有任何问题,但这当然取决于
temp
precip
的定义。您能否将这些添加到示例中,并展示函数的输出与您预期的不同?感谢您的编辑-这正是Fredrik在下面预期的问题(
size()
返回一个维度元组,因此您尝试创建一个范围
1:(7,)
,而不是范围
1:7
)或
eachindex(temp,precip)
而不是整个范围。是的,这也确保了两个数组的长度匹配。
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