At the end of your loop, you have only left a single method of your function fun. Every new definition on the next iteration redefines (overwrites) the same method. That’s why your code does not work as intended.
The syntax suggested in not complete, use this:
funvec = Vector{Function}(undef, 3);
for i in 1:3
fun = (theta) -> (println(i); cos(theta[1] ^ 3) + 5 * (theta[2] ^ 2) + 10sin(theta[3]) )
funvec[i] = fun
end
It’s the same. I just suspected that what’s happening is you’re overwriting the method for fun(theta) so maybe the anonymous function syntax would fix it.
As an attempt to explain the difference between what you and I encounter if it’s not related to the Julia version, could it be you already had (accidentally) defined fun outside of the loop?
E.g.
fun(x) = 0
funvec = Vector{Function}(undef, 3)
for i = 1:3
fun(x) = x * i
funvec[i] = fun
end
println(funvec[1](1)) # prints 3
println(funvec[1] == fun == funvec[3]) # true
In that case the explanation of @oheil and @DanielVandH would certainly apply.