(HOW) I need the code run again if the ( else condition return ) till give me value
Show older comments
Hi all. I have my code, and if the "if" condition is false for any value of i or j then it should stop and do the function again until the if condition true for all the values for i and j.
After else there is a return but it stops running and I run it again to get the (bestsol value) which do (Do this command line) and for loop again from the beginning. I need this code to run until I get (bestsol value) without it returning early.
I have used while true but it keeps running. Also I used while Halt==1 but work as no while loop.
function Labelvertices
%DO THIS LINES
%-----
%-----
%----
%-----Do this command line-------
verticeslabe=[0,randi(7)];
makematrix % it is function give us the matix d
for i= 1:7
for j=1:7
if (i~=j)
if % codition 1 met || codition 2 met
verticeslabe(i)= % do this;
verticeslabe(j)= % do this;
else
% does not meet codition 1 OR codition 2 go return to (do this command line) and do for loop again till we have (bestsol)
return ;
end
end
end
end
bestsol=verticeslabe(:,1:7) % this values i need it
end
1 Comment
Rik
on 27 Sep 2021
Return will exit the function, not just a loop.
Your code is too compact now. E.g. makematrix is either not a function, or you're not storing the result.
Perhaps you want to make your nested loop a subfunction that returns a second output: a valid flag. That way you can use a while loop and repeatedly call this until the flag is true.
Accepted Answer
More Answers (1)
Walter Roberson
on 27 Sep 2021
do_again = true;
while do_again
do_again = false;
for i= 1:7
for j=1:7
if (i~=j)
if % codition 1 met || codition 2 met
verticeslabe(i)= % do this;
verticeslabe(j)= % do this;
else
do_again = true;
break
end
end
end
if do_again; break; end
end
end
If the else is never executed, then do_again will not be set back to false, and the while loop will finish.
2 Comments
Image Analyst
on 28 Sep 2021
How do you guard against an infinite loop?
Walter Roberson
on 28 Sep 2021
The user requirements are clear, 'if the "if" condition is false for any value of i or j then it should stop and do the function again until the if condition true for all the values for i and j' . Stopping the function any time before the condition is true for all members of the array is contrary to the requirements to keep going until the condition is true for all the values for i and j -- even if that takes thousands of years.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!