I define t, then in a loop I'm told it's undefined, why?

The content of a loop is a local scope, which does no have access to the global scope. The following should work, using global:

t = 0.0;
# The actual integration
for i=1:N
    global t
    t = t + Simpson(h,y,i,N);
    y = y + h;
end

The following works as well (notice that tt is defined outside the outer loop.

tt = 0
for j in 1:10
    for i in 1:10
        global tt
        tt += 1
    end
end

Within a function, global is not required. The loop will work fine.

function simpson()
    t = 0.0;
    # The actual integration
    for i=1:N   
       # `global` is not valid within a function
        t = t + Simpson(h,y,i,N);
        y = y + h;
    end
end

I do not know whether global refers just to the scope outside the loop, or to the function, or the entire global space.

3 Likes