0
votes

Suppose I have the following code which has two nested while loops.

 struct Parameters

      maxIter1::Float64
      maxIter2::Float64

      tolerance1::Float64
      tolerance2::Float64

 end

 mutable struct Guess

      x1::Float64
      x2::Float64

 end

 function solveModel(par::Parameters,initGuess::Guess)

      iterate1 = 0
      error1 = 0

      guess = initGuess

      while (par.iterate1 < par.maxIter1 && error1 > par.tolerance1)

           iterate1 += 1

           iterate2 = 0
           error2 = 0

           guess.x2 = initGuess.x2

           while (iterate2 < par.maxIter2 && error2 > par.tolerance2)

                iterate2 += 1

                z2 = solveInnerProblem(par,guess)

                newGuess = update2(par,guess,z2)

                error2 = computeError2(newGuess,guess)

                guess = newGuess

           end

           guess = newGuess

      end 
 end

I get an error message,

enter image description here

Note: the reference to the line number is erroenous - line 294 of my code contains no mention whatsoever of newGuess.

The error message goes away if I comment out the line

 guess = newGuess    

In the outer loop (last line before the final two end lines in the code snippet). I'm quite confused as to why this is happening. The variable newGuess is clearly defined, but Julia says it is not defined...

1
The scope of the newGuess is within the innermost while loop. You can try moving the declaration outside of it (before the loop).Brian

1 Answers

2
votes

newGuess is a local variable, which means that it is defined in a localized part of the program rather than all the program. In the case of a local variable defined within a loop like a while statement, the variable is undefined outside the while loop within which it is defined, which is the inner while loop of your function. So the "not defined" error is because the program is trying to access the variable outside of its local scope-- it was defined before, but not when the error occurs.

You may need to define newGuess higher up, within the function, but before the inner while statement.