필터 지우기
필터 지우기

Nested while loop not working properly

조회 수: 3 (최근 30일)
flowguy
flowguy 2021년 5월 18일
편집: Shivani Dixit 2021년 5월 19일
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
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)
flowguy
flowguy 2021년 5월 18일
Yeah.... so obvious :)
I added the indice (i) to the term0, term1 and term2 to see the iterations properly.
Thanks David!

댓글을 달려면 로그인하십시오.

답변 (1개)

Shivani Dixit
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by