Nested while loop not working properly
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
David Fletcher
2021-5-18
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)
回答(1 个)
Shivani Dixit
2021-5-19
编辑:Shivani Dixit
2021-5-19
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!