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 Comment

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.

Sign in to comment.

Answers (2)

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.
While the condition y>2 is true, Matlab will stay in the loop. When the condition y>2 becomes false, Matlab leaves the loop

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 8 Jun 2015

Community Treasure Hunt

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

Start Hunting!