Nested while loop not working properly
2 views (last 30 days)
Show older comments
Hello guys,
I have a problem with nested while loops. The following code was supposed to give me term0=2 on the first iteration but it keeps giving me the value '8'.
From what I understand, this nested loop is supposed to do 'i=1' and then iterate k from 1 to 8, then end 'k' loop, do i+1 and k=1 and then start all over.
What am I missing here?
Thank you!!
i = 1;
j = 1;
k = 1;
S1= 0;
S2= 0;
while i <= 7
k=1;
S1=0;
while k <= 8
S1 = S1 + abs(V(k))*(real(Y(i+1,k))*cos(angle(V(i+1))-angle(V(k)))+imag(Y(i+1,k))*sin(angle(V(i+1))-angle(V(k))));
k = k+1;
end
term0=i+1;
term1=P(i+1);
term2=(abs(V(i+1))*S1);
deltaP(i) = term1-term2;
i= i+1;
end
2 Comments
David Fletcher
on 18 May 2021
I suspect it is doing exactly what is asked. You are not saving the values of term0 etc. so they will be overwritten on each iteration of the i loop. The value of 8 for term0 reflects the final value of term0 on the last iteration of the i loop (i=7+1 is 8)
Answers (1)
Shivani Dixit
on 19 May 2021
Edited: Shivani Dixit
on 19 May 2021
Your code is working fine as of assigning value to 'term0' (as expected), you are not able to view the value of 'term0'=2 because of reassignment at every iteration. The following example can illustrate how to analyse the above situation.
We can have two ways to resolve the above issue:
1. Using indexing of the variable 'term0', so that there is a proper understanding of what is going on inside the nested loop. Basically when we are not indexing 'term0' , what is happening is, the values assigned to 'term0' changes after every iteration , so what we have at last is the final vale of 'term0' that is 8. The following code illlustrates this :
i = 1;
j = 1;
k = 1;
S1= 0;
S2= 0;
% added index for term0 as idx_0
idx_0=1;
while i <= 7
k=1;
S1=0;
while k <= 8
%S1 = S1 + abs(V(k))*(real(Y(i+1,k))*cos(angle(V(i+1))-angle(V(k)))+imag(Y(i+1,k))*sin(angle(V(i+1))-angle(V(k))));
k = k+1;
end
term0(idx_0)=i+1;
idx_0=idx_0 +1;
%term1=P(i+1);
%term2=(abs(V(i+1))*S1);
%deltaP(i) = term1-term2;
i= i+1;
end
>> term0
term0 =
2 3 4 5 6 7 8
2. Another simple way could be just removing semicolon (;) after 'term0' so that when the code is executed all the values assigned to 'term0' after every iteration is displayed.
0 Comments
See Also
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!