I want to return back to a certain loop

I have 3 for loops(not nested for loops) and i want to check on the output coming from the third for loop and if it didn't satisfy a certain condition i want it to loop on the 3 loops again till it reaches an optimum solution! so can anyone help me please?

 Accepted Answer

Image Analyst
Image Analyst on 10 Mar 2016
Edited: Image Analyst on 10 Mar 2016
Try something like this
again = true
loopCounter = 1
maxIterations = 1000 % Whatever, to prevent infinite loop
while again && loopCounter <= maxIterations
for k1 = 1 : k1Max
% Code
end
for k2 = 1 : k2Max
% Code
end
for k3 = 1 : k3Max
% Code to set some condition
end
if yourCondition == successCriteria
again = false;
end
loopCounter = loopCounter + 1; % Increment loop counter
end

4 Comments

Not sure why you tagged this "recursion" I don't think a solution involves any code calling itself.
My guess is Fangjun tagged it 'recursion' based on the approach used by the other Answer currently available for this question.
Oh, I see now. That wasn't there when I put my responses in.
No. I didn't tag anything and I never saw it. A recursive function is the first thing came to my mind when I read the question.

Sign in to comment.

More Answers (1)

Fangjun Jiang
Fangjun Jiang on 10 Mar 2016
Edited: Fangjun Jiang on 10 Mar 2016
There is no "goto" statement in MATLAB if that is what you are looking for. I think your task could be solved with a recursive function. There is nothing special in MATLAB regarding recursive function. Just search for "recursive function" or "recursive function example" on the web.
function out=MyFun(input)
% do loop 1
% do loop 2
% do loop 3
if out==GOOD
return;
else
out=MyFun(input); % could use modified input if needed
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

N.
on 10 Mar 2016

Commented:

on 10 Mar 2016

Community Treasure Hunt

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

Start Hunting!