Global variable cannot be read within if-else-loop

Here is a sample code I have created:

function fn_update_a(a, b, c, d)
   a = fn(c,d)
   b = vcat(b,a)
   return a, b
end

for isim in 1:10
   a = fn(c, d)
   if isim==1
      b = deepcopy(a)
   else
      a=1
      println(b)
      (a,b) = fn_update_a(a,b,c,d)
   end
end

My question is why there is an error saying “b is not defined” at line after a=1 when b=deepcopy(a)?

Because b = deepcopy(a) will only be run if isim == 1, and println(b) will be run otherwise (when isim != 1).
The b definitions are local to that iteration of the loop. You could write global b.

2 Likes

Thank you.