How to use the break command in nested loops?

2 次查看(过去 30 天)
Hi, I have a problem using the break command in the following code. When I use the break I exit the loop j, but I want to restart the loop i after the condition. Any idea how can I do in this case? Thanks inm advance.
for i = 1:length(initial_solution.position) - 1
itabu = i;
for j = i + 1:length(initial_solution.position)
jtabu = j;
t = CHECK_MOVE(itabu, jtabu, TL);
if (t == 1) % 0 or 1 / True or False / Tabu or not Tabu
break
end
neighbor.position = SWAP(initial_solution.position, itabu, jtabu);
% Evaluate Objective Function
neighbor = EVALUATE_OF(neighbor);
% Update best neighbor
if neighbor.OF >= best_neighbor.OF
best_neighbor = neighbor;
end
end
end
  1 个评论
AndresVar
AndresVar 2022-2-17
i think you need another outter while loop to repat the whole thing. And a flag to tell it to stop when all the i and js were done.

请先登录,再进行评论。

回答(1 个)

David Hill
David Hill 2022-2-17
编辑:David Hill 2022-2-17
while 1
flag=0;
for i = 1:length(initial_solution.position) - 1
itabu = i;
for j = i + 1:length(initial_solution.position)
jtabu = j;
t = CHECK_MOVE(itabu, jtabu, TL);
if (t == 1) % 0 or 1 / True or False / Tabu or not Tabu
flag=1;
break
end
neighbor.position = SWAP(initial_solution.position, itabu, jtabu);
% Evaluate Objective Function
neighbor = EVALUATE_OF(neighbor);
% Update best neighbor
if neighbor.OF >= best_neighbor.OF
best_neighbor = neighbor;
end
end
if flag
break;
end
end
if ~flag
break;
end
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by