Reputation: 21
I defined a function m(r,T,a,w)
and I have vectors for the variables r,T,w.
What I want to do is to take the first element of each of those vectors and iterate my function for a in 1:T
, then take the sum and repeat this iteration for the second element of those vectors and so on.
In the end I want to have a vector consisting of all the sums.
I would appreciate your help.
What I tried so far:
(W
,R
,LE
are the vectors for the variables for w
,r
,T
, respectively)
M = []
for w in W, r in R, T in LE
for a in 1:T
MM=sum(m(r,T,a,w))
push!(M,MM)
end
end
clearly Julia would not recognise what Im trying to do
Upvotes: 1
Views: 129
Reputation: 21
Thanks for the very helpful comments. I managed to code what I wanted
MM = Vector{Float64}()
M = Vector{Float64}()
for (w, r, T) in zip(W, R, LE)
for a in 1:T
push!(MM, m(r,T,a,w))
end
push!(M,sum(MM))
end
Upvotes: 0
Reputation: 1750
Matt's answer is correct, but you might want to improve a few other things, such as the types, and putting this in a function so that it isn't using a global variable. Do you know what the type of the sum is? Would a Float64
work, or a Int64
?
For example:
function myfun(W, R, LE)
M = Vector{Float64}()
for (w, r, T) in zip(W, R, LE), a in T
push!(M, sum(m(r, T, a, w)))
end
M
end
Upvotes: 0
Reputation: 31342
The syntax:
for w in W, r in R, T in LE
...
does not iterate over the vectors at the same time. Rather, it is equivalent to the product:
for w in W
for r in R
for T in LE
...
It sounds like you want to iterate over those three vectors at the same time. In that case, you can use zip
:
for (w,r,T) in zip(W,R,LE)
...
Upvotes: 4