# Two index-summation loop

Hi everyone.

I am trying to program the following summation into Julia:

y_i = c_i + \sum_{r=1}^{i-1} b_r*y_{i-r}

So for example, in the following toy numerical example:

using DataFrames
test = DataFrame(months = 0:3, y = 0
test[!,:y] = convert.(Float64,test[!,:y])
c_test = [0,1,1.1,1.2]
b_test = [0,2,2.1,2.2]


the correct code would spit out the following column-vector (working out can be provided if required):

y' = [0,1,3.1,9.5,29.01]

I tried different ways of using forloops but got nowhere with them. I know the following lines are completely wrong but I donβt know where to even begin to fix it

for i in 2:nrow(test)
for r in 2:nrow(test)
test[i,2] = c_test[i,1] + sum(b_test[r,1]*test[i-r,2])
end
end


Any help would be really appreciated, tysm!

I think your βcorrect resultβ is wrong

julia> for i in eachindex(y)
second_term = 0.0
for r=1:i-1
second_term += b_test[r] * y[i-r]
end
y[i] = c_test[i] + second_term
end

julia> y
4-element Vector{Float64}:
0.0
1.0
1.1
3.2

1 Like

It seems the expression you want is:
y_i = c_i + \sum_{r=1}^{i-1} b_r*y_{i-r+1}

i.e. y_{i-r+1} instead of y_{i-r} . Implementing that gives the result you expect.

julia> test= DataFrame(months = 0:3, y = 0.0)
4Γ2 DataFrame
Row β months  y
β Int64   Float64
ββββββΌβββββββββββββββββ
1 β      0      0.0
2 β      1      0.0
3 β      2      0.0
4 β      3      0.0

julia> for i in 1:nrow(test)
test.y[i] = c_test[i]
for r in 1:i - 1
test.y[i] += b_test[r] * test.y[i - r + 1]
end
end

julia> test
4Γ2 DataFrame
Row β months  y
β Int64   Float64
ββββββΌβββββββββββββββββ
1 β      0      0.0
2 β      1      1.0
3 β      2      3.1
4 β      3      9.5

1 Like