In the original version the y variable is local to each iteration of the loop. You can see that here, for example:
julia> function f(x)
for i in 1:2
if i == 2
println(" i = ", i)
println(y)
end
y = x
println(" i = ", i, " y = ", y)
end
end
f (generic function with 1 method)
julia> f(1)
i = 1 y = 1
i = 2
ERROR: UndefVarError: y not defined
Stacktrace:
[1] f(::Int64) at ./REPL[12]:5
[2] top-level scope at REPL[13]:1
julia>
When you add the local y or set y = something outside the loop, y becomes a variable in the scope of the function, and then it works:
julia> function f(x)
local y
for i in 1:2
if i == 2
println(" i = ", i)
println(y)
end
y = x
println(" i = ", i, " y = ", y)
end
end
f (generic function with 1 method)
julia> f(1)
i = 1 y = 1
i = 2
1
i = 2 y = 1
julia>
Note that, even with the local y declaration, your function throws an error if I == 0, so not initializing y to a starting value before the loop is arguably an indication of a bug.
It looks like what you really want might to eliminate the y variable completely, since it seems redundant:
function ricky(x, k, r, I)
for i = 1:I
x *= exp(r * (1-x/k))
end
return x
end