Break statement inside an if statement
74 views (last 30 days)
Show older comments
for count = 1:Iteration_lim + 1
%Error check for function not converging
if count == Iteration_lim + 1
error('Iteration limit reached, function failed to converge.')
break
end
This is a section of my code, when I put in the break statement I get an error saying "This statement (and possibly following ones) can not be reached". The code runs and returns a final answer but the break statement does not seem to be doing anything. This is problematic as I want to return the count and the equivalent answer at that iteration, not just the final answer, at the end of the for loop. My professor has uploaded identical code which performs this task without problem. Any help is appreciated.
0 Comments
Answers (2)
Geoff Hayes
on 3 Apr 2020
Darragh - the error throws an error and displays a message, so the break will never be called...and so the error message makes sense (I get the same error when using it in my code). To get around this, change the error to an fprintf like
fprintf('Iteration limit reached, function failed to converge.\n');
11 Comments
Geoff Hayes
on 7 Apr 2020
Have you tried stepping through the code to check if the results at each line make sense? Are the angles in angleset reasonable?
Darragh Tobin
on 8 Apr 2020
1 Comment
Geoff Hayes
on 8 Apr 2020
I suspect that "count' produces a value that might be unused." is a warning and not an error so it can be ignored. You are right that having "count;" on the second line does nothing at all. The problem with the convergence probably has nothing to do with this but may instead have something to do with your implementation of the code. Presumably when you say that fails to converge for all input values you mean that you don't get the correct answer and that your code always reaches the maximum number of iterations. Is this correct?
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!