How to stop a loop without loosing the generated data?

For your first bit of code, you may use a local variable, to ensure that xᵏ is available throughout the whole function, instead of only inside the for loop.

zub=1000
function initiate()
    local xᵏ # <-- this sets xᵏ’s scope
    for k in 1:10
        optimize!(p1)
        xᵏ=value.(x)
        o¹=objective_value(p1)
        if o¹ > zub
            break
        end
    end
    return xᵏ
end

For your second code block, the problem is that the variable zub in the function

zub=1000
function initiate()
    …
    if o²+o¹ < zub
        zub=o²+o¹
    end
end

occurs first as the result of an assignment, so it is assumed to be a local variable. You may declare it a global variable to fix that:

zub=1000
function initiate()
    …
    if o²+o¹ < zub
        global zub=o²+o¹
    end
end

(See the performance tips regarding global variables.)

1 Like