function test_reason()
for i = 1:10
if i == 1
x = 1
else
x = x+1
end
end
end
test_reason()
It seems that it has some scope problem but it’s strange that I have alread define a fucntion for it.
See the loop scoping rules, in particular this part:
[N]ew variables introduced in their body scopes are freshly allocated for each loop iteration
You need to define x
outside the loop if you want it to persist beyond each loop iteration.
julia> function test_reason()
local x
for i = 1:10
if i == 1
x = 1
else
x = x+1
end
end
return x
end
test_reason (generic function with 1 method)
julia> test_reason()
10
5 Likes
That’s helpful.
Thank you.
Or
function test_reason()
x = 1
for i = 1:10
if i > 1
x = x+1
end
end
return x
end
Even simpler:
function test_reason()
x = 0
for i = 1:10
x = x+1
end
return x
end
Or (though I expect this is just due to an overly M MWE):
test_reason() = 10