how to go back in previous iteration

i was trying to run an iterative process in while loop.it is conditional based iteration, if the condition is satisfied in current iteration then continue to next iteration else go to previous iteration as long as condition is not satisfied.
i have considered iter=iter-1 for previous itertion in if loop and then used break command to terminate while loop . will it go back in previous iteration with this condition. suggestion will be appreciated.
thanks in advance...

 Accepted Answer

The only way to go back to a previous iteration is to use a while loop and make the loop counter the appropriate previous value and then "continue".
It is much more common to want to stay on the current iteration until a condition is satisfied. For that, you can use a while loop within a for loop
for K = 1 : number_of_iterations
while true
do a calculation
if condition is satisfied
break
end %end if
end %end while
end %end for

5 Comments

but in my problem the current output is dependent upon the previous output. so if current output condition is not satisfied it need to go back in previous output and made suitable change so current condition is satisfied
Then you can use a while loop and set the loop control variable to the previous value and "continue". For example,
i = 1;
while i < 10
disp(i);
if i < rand()*10
i = max(1, i - 1);
continue;
end
i = i + 1;
end
i have used for loop for 24 interval then while loop in nested and if command for conditional violation is used e.g. if 12th interval condition is not satisfied then it should go 11th interval but for loop is used for interval so how will for loop go back in 11th interval if 12th interval loop is run. for loop is used for interval so it can not be eliminated. example as given below
for i=1:24
count=1;
maxcount=100;
while index==0
if condition satisfied
index=1
break
end
count=count+1;
if count>maxcount
i=i-1;
break
end
end
end
If someone has imposed a constraint on you that a for loop must be used, then you will need to rethink your implementation.
Otherwise just convert the for loop to a while loop
i = 1;
while i <= 24
....
end
and remember to increment i when you are ready to move forward.
i got the answer thank you for your valuable suggestion

Sign in to comment.

More Answers (0)

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!