Scope of variables

Hi,
I’m having trouble to define the scope of a variable in a simple Lagrange interpolation code, i got this “UndefVarError: i not defined”. I wonder how can i define this “i” variable, it should be local as it is used in a for loop.
The code is something like this:

x = [-2.0, -1.0, 0.0, 1.0, 2.0]
y = [-9.0, -15.0, -5.0, -3.0, 39.0]

println("Enter number of terms")
n = parse(Int32, readline())

println("Enter xx for interpolation")
k = parse(Int32, readline())

s = 0.0

for i = 1:n
    p = 1.0
    for j = 1:n
        if(i != j)
            p = p + ((k - x[i]) / (x[i] - x[j]))
        end
    end
end

s = s + (p * y[i])
println(s)

Thanks in advance.
Cheers,
João Rocha

1 Like

i is not defined here and I can’t see which value of i you expect.

The loop variable i is not defined outside the body of the loop (unless you use the outer keyword).

1 Like

Thanks @oheil and @stevengj, of course it could not work outside the loop. It skiped me. It works now.
Thank once more.
Cheers.

2 Likes