How to stop a loop without loosing the generated data?

I work on an iterative algorithm. The simplified version of it is

Step 1: optimize problem1
Step 2: if objective_function_of_problem1 > zub exclude the answer and go to the step 1
Step 3: optimize problem2 with data pertaining to the solution of p1
Step 4: if objective_function_of_problem1 + objective_function_of_problem2 < zub then update zub = function of problem2

I do this for step 1 and 2:

zub=1000
function initiate()
    for k in 1:10
        optimize!(p1)
        xᵏ=value.(x)
        o¹=objective_value(p1)
        if o¹ > zub
            #@constraint for excluding the answer ......
            break
        end
    end
    return xᵏ
end

UndefVarError: xᵏ not defined

It looks like after break the data is lost.
Is it possible to stop the iteration with a condition without losing the data?

I wrote below code for step 4

zub=1000
function initiate()
    optimize!(p1)
    o¹=objective_value(p1)
    o²=solve_p2(xʳ)[1]
    if o²+o¹ < zub
        zub=o²+o¹
    end
end
UndefVarError: zub not defined

But it says zub is not defined. I defined it in the first line!

Thanks!

I would have suggested to put it in a function, but it already is. Just move the return up to where the break is.

And you need zub to be available inside the function. Either define it inside, make it an input argument or make it a global.

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