Variable accessibility within loops

Hello,

The following code runs for iteration 1, printing the “mindi” variable. However, it throws an error for iteration 2. It says mindi is undefined. Why is the variable inaccessible for the second iteration?

maxiter = 10000
tol = .00000001
iter = 1                                                #initalize iterator 
maxdi = 1000                                               #initalize difference, arbitrary large number 

v = zeros(nz,nk)
while ((iter < maxiter) & (maxdi > tol));
    q = P*v;
    qlong = fillin(q)

    #first iteration use full bellman, then limit 
    if iter < 2
        res = maxbellman(qlong)
    else 
        print(iter)
        res = mc_maxbellman(qlong,maxdi,mindi)
    end

    maxdi = findmax(abs.(res.v - v))[1];
    mindi = findmin(abs.(res.v - v))[1];

    global v = res.v
    global l = res.k
    iter = iter + 1 

    println(maxdi)
    println(mindi)
end;
1 Like

In each iteration of the while loop, mindi is defined towards the end and only lives until the while loop iteration is done, because it only exists in the while loop’s scope.

You have an if else statement before the definition of mindi and in iteration 2 it takes the else branch which accesses mindi before it is created again. In iteration 2, the variable mindi from iteration 1 doesn’t exist anymore.

If you want it to persist, you can write local mindi before the while loop, so that you don’t have to define its value before while iteration 1, but it still lives across iterations because its scope is outside of the while loop.

2 Likes