Matlab general question ("while" function)

Hello, I just wanted to ask if someone could please explain this code to me? I'm not too sure on how the "while" function works. I thought the value for jj would be 2 because "y" is dependent on "jj" but not the other way around? But the value for jj is 4.
jj = 1;
y=2^5;
while y > 2
y=y*2^(-jj);
jj = jj + 1;
end
Thankyou!

댓글 수: 1

The loop was executed three times. After the first time execution jj=2 and y=16. This is because every time the loop executes, jj is incremented by 1. After executing the while loop for the first time, the value of y was still greater than 2, so the loop executed again.
This time, the values of jj and y from the previous iteration are used. and after this iteration the ne values were jj=3 and y=4
as you can see, the value of y is still greater than 2 and so the loop still has to execute for the third time. The new values after this third exceution are jj=4 and y=0.5.
The loop will stop executing from this stage because the value of y is now less than 2.

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

답변 (2개)

Guillaume
Guillaume 2015년 6월 8일

0 개 추천

jj does depend on y and the whole purpose of the loop appear to be to calculate a jj based on the value of y.
The loop divides y by a power of 2, 2^jj, and if that is not strictly smaller than 2 loop around. The result of looping around is that the result of the previous division is divided by the next power of 2. jj is thus the value for which y / 2^1 / 2^2 / ... / 2^jj < 2.
The best way for you to understand what the code is doing is to step through it one line at a time using the debugger and look at the values of the variables as you step through.
A few notes:
  • Use variables names that have meaning. Use as many letters as necessary.
  • Whenever you use unusual operations, comment the code to explain what is going on.
  • I would have written a division ( y = y / 2^jj) rather than a multiplication. I inherently assume that a multiplication is going to increase the value, so my first reaction was that the while loop would never terminate. I feel that a division better conveys that y decreases with the loop.
Azzi Abdelmalek
Azzi Abdelmalek 2015년 6월 8일

0 개 추천

While the condition y>2 is true, Matlab will stay in the loop. When the condition y>2 becomes false, Matlab leaves the loop

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2015년 6월 8일

댓글:

2015년 6월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by