How can I insert a while loop inside a for loop on Matlab without having to manually stop the run?
Show older comments
So I am using a while loop inside a for loop to stop the iteration at the condition written next to "while" in the code shown in the link below: Matlab Code

The run is not ending on Matlab but when I pause the run, I see right answers for h1 & h2 & h3 & h4. I just need the run to end by itself without having me to impose the stop. How can I solve this problem?
1 Comment
Jan
on 26 Apr 2022
The shown code does not run: it should stop at zeros(inf, 1). Did you redine "inf" as a variable as you did for "error"? Do not do this, because shadowing built-in functions by local variables cause confusion.
If the while loop does not stop, the condition is not fulfilled. What you have to change is clear: Use a matching condition. We cannot know, what you need here.
Please post code as formatted text and not as screenshot.
Answers (1)
One thing is, you probably mean to have abs in the while condition. That is, say h1(i)-h1(i-1)==-1000 (and the same for h2, etc.). Then the loop will continue because -1000<=0.0001. But maybe you want the loop to stop because 1000>0.0001
while abs(h1(i)-h1(i-1))<=error && ... % etc.
In addition to that, maybe the inequalities should go the other way. That is, maybe you want to iterate while abs(h1(i)-h1(i-1))>0.0001 etc., which is to say, keep going as long as those two consecutive elements of h1, h2, etc., are not within error of each other (and stop when any of them are within error):
while abs(h1(i)-h1(i-1))>error && ... % etc.
Or, more likely, I think, you would want to stop when all of them are within error (so keep going as long as any are > error):
while abs(h1(i)-h1(i-1))>error || ... % etc.
Basically you need to think carefully about what that while condition should be. It may be easier to put it in terms of when to stop the loop rather than when to continue the loop (which is implied in your phrasing of the question).
The idea is that this:
while (when to keep going)
% do stuff
end
is the same as this:
while true
if (when to stop)
break
end
% do stuff
end
where the conditions (when to keep going) and (when to stop) are opposites of each other (i.e., one is true when the other is false and vice versa).
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!