I'm Trying to run iterations until convergence.
Show older comments
Hello,
So baically I have a problem where I am guessing an initial weight (Wi). and then I have to plug in (Wi) into an Equation that looks like this. W6=Wi*(0.95)*(0.97)*...
Then I want to take the answer for W6 and use it in this equation (Y=W6/Wi). Then take the answer for Y plug it into another equation F=(1-Y)*1.06.
Lastly from there, take all these answers I just found and plug into Wtogw=(25000)/(1-F-0.457).
Now. Whatever answer I get for Wtogw, I want to use that as my new Wi and redo the process unti the answer I get for Wtogw is equal to Wi.
I have posted what I have so far. The whole first part of code is just setting variables which have known values. Please tell me what I am doing wrong/missing for the "while" loop.

Answers (1)
Well, you haven't actually told us what the problem you're encountering is, but right away I can see several problems. First, your while loop condition is i<=maxIter, but you haven't defined i anywhere. As a result, MATLAB is using the built-in i, i.e., sqrt(-1). In this case, when checking whether i<=maxIter, MATLAB only considers the real part of i, which is 0, and therefore (i<=maxIter) evaluates to true.
Furthermore, since i isn't changing inside the loop, it will always be the case that i<=maxIter, and therefore your loop will never end.
If you want to do this loop a set number of times, you should use a for loop, not a while:
for i = 1:maxIter
<stuff>
end
7 Comments
Cole Zajack
on 23 Sep 2020
Cole Zajack
on 23 Sep 2020
Dana
on 23 Sep 2020
To check for convergence:
% set a convergence tolerance (best choice depends on the specifics
% of your application; you might have to play with this
tol=1e-6;
noconv=true; % = true if convergence hasn't been obtained yet
j=0; % counter to track # of loop iterations
while noconv
j=j+1; % advance loop counter
.
. % your lines up to and including Wtogw = ...
.
% if either Wtogw is close to Wi, or we've reached the
% max # of iterations, set noconv=false so there's no more
% iterations after this one.
if abs(Wtogw-Wi) < tol || j == maxIter
noconv=false;
end
Wi=Wtogw; % update Wi
end
Cole Zajack
on 23 Sep 2020
Dana
on 23 Sep 2020
Where you had it before, or really anywhere before the start of the loop.
Cole Zajack
on 23 Sep 2020
Dana
on 23 Sep 2020
MATLAB interprets the statement i<=maxIter as, "Check whether i is less than or equal to maxIter; return true if it is, return false if it's not."
That's not what you want to do here. Rather, you simply want to define maxIter, just as you did originally:
maxIter = 100;
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!
