Issues with undefined variables in loops?

I am running a center finite difference method with temporally dependent boundary condition. The following code runs fine.

dirichlet=1
for Δt in range(2,stop=length(t_array)-1, step=1)
    for Δx in range(1,length=Nx)
        if Δx == 1
            p_series[Δt+1,Δx] = 2*p_series[Δt,Δx]-p_series[Δt-1,Δx]+((δt^2*c0^2)/δx^2)*(p_series[Δt,Δx+1]-2*p_series[Δt,Δx]+dirichlet)
        elseif Δx == Nx
            p_series[Δt+1,Δx] = 2*p_series[Δt,Δx]-p_series[Δt-1,Δx]+((δt^2*c0^2)/δx^2)*(dirichlet-2*p_series[Δt,Δx]+p_series[Δt,Δx-1])
        else
            p_series[Δt+1,Δx] = 2*p_series[Δt,Δx]-p_series[Δt-1,Δx]+((δt^2*c0^2)/δx^2)*(p_series[Δt,Δx+1]-2*p_series[Δt,Δx]+p_series[Δt,Δx-1])
        end
    end
end

however when I add an if statement to set the boundary to be 0 after a number of time steps using…

dirichlet=1
# Start time loop
for Δt in range(2,stop=length(t_array)-1, step=1)
    if Δt == 10
        dirichlet=0
    end
    for Δx in range(1,length=Nx)
        if Δx == 1
            p_series[Δt+1,Δx] = 2*p_series[Δt,Δx]-p_series[Δt-1,Δx]+((δt^2*c0^2)/δx^2)*(p_series[Δt,Δx+1]-2*p_series[Δt,Δx]+dirichlet)
        elseif Δx == Nx
            p_series[Δt+1,Δx] = 2*p_series[Δt,Δx]-p_series[Δt-1,Δx]+((δt^2*c0^2)/δx^2)*(dirichlet-2*p_series[Δt,Δx]+p_series[Δt,Δx-1])
        else
            p_series[Δt+1,Δx] = 2*p_series[Δt,Δx]-p_series[Δt-1,Δx]+((δt^2*c0^2)/δx^2)*(p_series[Δt,Δx+1]-2*p_series[Δt,Δx]+p_series[Δt,Δx-1])
        end
    end
end

I get…

ERROR: UndefVarError: dirichlet not defined
Stacktrace:
 [1] top-level scope at ./REPL[254]:8 [inlined]
 [2] top-level scope at ./none:0

I am not quite seeing why this error comes up.

You are using global variables in the repl, which now needs an explicit global declaration. (There are various posts on discourse about this.)

The solution to this is to wrap everything in a function, which will also significantly improve performance.

3 Likes

An alternative workflow is to “play around” prototyping things in Jupyter (which will behave the way you are expecting) and then wrap in a function when you want to move it into a .jl file.

3 Likes

Thanks! I was mainly just using it to “play around”, so I am not too worried about performance right now.

I may check out Jupyter again, but I was just writing a small script to understand the problem.

Most people like to do their “scripts” in jupyter, and then put things into real functions in the .jl files with Atom. If you use that approach, you will never run into this issue again.