Undefined variable of function side while loop

I have a function inside a while loop like the code below, but get problem ERROR: UndefVarError: Pre_predict not defined.

Pre_predict = zeros(Row, Col)
while true
    N,S,W,E,C,Q = construct_Tran_matrix(Pre_init, **Pre_predict**, Gamma, Z_init, Z_predict, Order)
    LHS, RHS  = construct_Coefficient_matrix(N,S,W,E,C,Q,Order,cnt)
    Residual_matrix = Residual(LHS, RHS, Pre_predict, Order, cnt)
    J = Jacobian_matrix(Pre_predict, Order, Gamma, Z_predict, cnt)
    Delta_p = J\Residual_matrix
    if maximum(broadcast(abs, Pre_predict-Pre_init)) < 0.01
        break
    end
end

BUT when I change to variable X = 5, it works.

X = 5
while true
    N,S,W,E,C,Q = construct_Tran_matrix(Pre_init,  **X**, Gamma, Z_init, Z_predict, Order)
    LHS, RHS  = construct_Coefficient_matrix(N,S,W,E,C,Q,Order,cnt)
    Residual_matrix = Residual(LHS, RHS, Pre_predict, Order, cnt)
    J = Jacobian_matrix(Pre_predict, Order, Gamma, Z_predict, cnt)
    Delta_p = J\Residual_matrix
    if maximum(broadcast(abs, Pre_predict-Pre_init)) < 0.01
        break
    end
end

Can some one explain the problem with my code?

It looks like you need a let block. See also https://docs.julialang.org/en/v1/manual/variables-and-scoping/

julia> y = 10
10

julia> while y < 100
        y += y
       end
ERROR: UndefVarError: y not defined
Stacktrace:
 [1] top-level scope at .\REPL[8]:2

julia> let y = 10
        while y < 100
         y += y
        end
        return y
       end
160
2 Likes

Thank you. I got it.

Perfect, you’re most welcome.