# How do I update a variable in a nested loop?

50 views (last 30 days)
Timothy Chau on 16 Dec 2020
Answered: Walter Roberson on 16 Dec 2020
When I'm running this code, the variable "iter" updates in the outer while loop but it's not updating in the inner while loop. Iter in the outer while loop returns 1, 2, 3, 4, 5 after 5 iterations but the iter in the inner while loop returns 1, 1, 1, 1, 1 after 5 iterations. Is there a way to update iter in the inner while loop?
Here's while loops part of my code:
iter = 1; % Initial iteration
while iter<6 % Outer while loop
while n*dTm<W
n = n+1;
if n==16
break
end
while d>.05*dTm % Inner while loop
phi = atand((vi+vc)/(w*r*.2*iter));
alpha = theta - phi;
Cl = CL(find(ALPHA_CL > alpha, 1));
dTa = .5*rho*(w*r*.2*iter)^2*c*dr*Cl;
dTm = 4*pi*r*.2*iter*dr*rho*vi*(vi+vc);
d = abs(dTm-dTa);
vi = vi+1;
if vi==1000
break
end
end
vi;
dTm;
end
x(iter, 1) = iter;
x(iter, 2) = vi;
x(iter, 3) = dTa;
x(iter, 4) = dTm;
iter = iter+1;
end

Jon on 16 Dec 2020
If you want iter to increment inside of the inner loop you have to move the statement
iter = iter+1;
inside of the inner loop.
However, although I don't know the details of what you are doing here, it seems like you may want iter to stay constant while the inner loop iterates. So maybe your code is already doing what you want.
Also, if you know you want a loop to execute a known number of times, 6, in your case, you should use a for loop instead of a while loop, e.g. for k = 1:6 .... end
Timothy Chau on 16 Dec 2020
I don't want to put iter inside the inner while loop because I don't want it to increment everytime the inner while loop is done. I want the 2 inner while loops to finish before iter is incremented, hence why it's in my outer while loop, then after iter is incremented, I want the 2 inner while loops to be executed again but with the new value of iter. The problem is, iter is incrementing in the outer while loop, returning 1, 2, 3, 4, 5 after 5 iterations, but not updating in the inner while loop, returning 1, 1, 1, 1, 1 after 5 iterations.

Walter Roberson on 16 Dec 2020
while n*dTm<W
n = n+1;
if n==16
break
end
After the end of the inner loop, you are not changing n, dTm, or W, so if you left the inner loop because n*dTm<W was false, it will still be false.
If you left the inner loop because n == 16 was true, then n will be incremented to 17 because the n=n+1 is before the test, so you will not break because of that. You will, though, then execute the inner loop with n = 17, leaving it when n*dTm<W becomes false, and then the outer iteration after that, you are back to the problem I described in the first paragraph.

### Community Treasure Hunt

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

Start Hunting!

Translated by