Indexed variable inside function and for loop

#1

Hi everyone. I have a simple doubt about whether is possible to have an index number inside a function in a for loop. The ilustrative example below makes my doubt clearer.

I have an affine function f(x) = 2x - a and I want to find the root for distinct values of a. In this case, is it possible to use the fzero function inside a loop?

I understand why the error occurs but I do not know how to fix it. I have a similar code in Fortran and I am trying to convert it to Julia.

Thanks a lot!


a = [1 3 5]

function main(x)
    2*x - a[i]
end # function

guess = 5
for i in 1:3
    y = fzero(main, guess)
    println(y)
end # for

UndefVarError: j not defined
0 Likes

#2

If I understand your problem correctly (please submit fully reproducible code to make it easier for us!), a common way to deal with it in Julia is to have the method take the index, and then bind the index to the function to create a single-parameter function:

a = [1 3 5]

function main(x, i)
    2*x - a[i]
end

guess = 5
for i in 1:3
    y = fzero(x -> main(x,i), guess)
    println(y)
end
1 Like

#3

Another possibility is doing the following:

a = [1 3 5]

function main(x, b)
    2*x - b
end

guess = 5
for i in 1:3
    b = a[i]
    y = fzero(x -> main(x,b), guess)
    println(y)
end

This will probably run faster, unless you declare a constant with const a = [1 3 5] in your original code, then I guess both will have the same speed.

But the key concept you are looking for here is that of anonymous functions.

EDIT: Modifying according to what bennedich pointed out.

1 Like

#4

Thanks!

0 Likes

#5

Thanks.

0 Likes

#6

I think it’d actually be the same, since the indexing would still take place for each function call. You’d have to move it outside the function for the speedup to occur:

for i in 1:3
    b = a[i]
    y = fzero(x -> main(x,b), guess)
    println(y)
end
1 Like