[MUSIC] For-loops work well when we know
the maximum number of necessary iterations before entering the loop. In a control statement, the expression
is evaluated and then the loop index will receive the elements of the vector or
the columns of the array one by one. Maximum number of times the for loop body
will execute is fixed at this point. Why maximum? Because we can always quit early
with the a break statement. What if we don't know the maximum number
of times the loop needs to iterate? Consider this problem. How many positive integers do we
need to add together to exceed 50? The only way to solve this with a for-loop is to guess a large enough number for
the number of iterations and use a break statement to stop
the loop when 50 is exceeded. You can do that. It's not that hard for
this simple problem. But there's a better way. One with no guesswork at all,
a while loop. Check this function out, we call it
possum, for positive integer summation. It takes the limit that we want
to exceed as an input argument. It both prints and returns both the number
of positive integers we need to add together to exceed the input value and
the sum of those integers. We start by setting both n and
total to zero. Then we use the new while
keyword followed by a condition. The meaning is simple. If the condition is true,
we execute the body of the while loop. The body is the set of statements between
the while line and the end keyword. Once we execute the body, we go back and
check the condition again. If the condition is false, the while
loop is done, otherwise it continues. The body in this example increments n
by 1 and then adds the result to total. Once total exceeds limit,
the while condition will be false, the loop terminates, and
we print the result. The function then terminates and
returns its output argument. If we run the function with the input 50,
here's the result. The first line of the printout came
from the fprintf inside the function. Then MATLAB caught the first output
argument in its ands variable, and echoed the result. The second output argument was discarded. Well we've seen the while loop in action. Let's take a closer look at its form. Just like the for loop, the while loop
has a control statement and a body. However, the control statement of a while
loop is a condition like, for example, total less and than or equal to limit. Its value is either true or false. If it's true, we execute the body. Then, we check the condition again. If it's false, we quit. You might have noticed that
the general form of the while loop is very similar to that
of the if statement. In fact, syntactically, the only difference is the different
keyword, while, instead of if. But semantically, they are very different. The if statement's a one-shot deal. If the condition's true,
we execute the body and we're done. But the while loop keeps
checking the condition and executing the body over and over and
over until the condition becomes false. This is a very powerful and
very flexible way of looping. Let's look at this example in MATLAB. Here's the possum function in
the editor window right here. Let's run it.
[SOUND] [SOUND] Okay let's check its answers. Let's look at the last example first. We can do that by checking
the sum of 1 through 318 and then the sum of 1 through 319. Like this. [NOISE] Okay, 318 isn't large enough to get the sum above 51,000, but 319 is. And the sum to 319 is 51,040. Which agrees with the answers up here. So the answers are correct. You can check the other examples, too. You'll find they're all correct. This function works like a charm. But before we leave it,
let's talk a little more about its form. We pointed out how similar a while
loop is to an if statement. But notice how similar this particular
while loop is to a for loop. Not only does it iterate, but
like a for loop, on each iteration, our while loop increments in, right here. Which is a kind of loop index. And it starts out in initial value, here. And terminates when it
reaches it's last value. I say kind of, because this
so-called loop index you're in is not an integral part of the while
loop control statement up here. In the way that an index of a for loop is. The index of the for loop is an integral
part of the for loop control statement. The syntax requires it. And the for loop semantics is based on it
too, because the number of iterations is completely determined by
the list of values for the for loop index given in the control statement. And then the index is assigned a new
value from that list on every iteration. In fact, as we showed earlier in this
lesson, you can change the for loop index to whatever you want in the body of the
loop and on the next iteration, it'll be changed right back to the next item of the
list by the for loop control construct. The while loop on the contrary, doesn't
provide a list of values for an index and it doesn't increment
anything on any iteration. If we want to increment something,
we've got to do it ourselves. Explicitly, with a statement
in the body of the loop as we have here with this n
equals n plus 1 statement. The index is not part of the while loop
syntax at all or the while loop semantics. And to drive that point home, I'm going to show you a perfectly good
while loop with no loop index at all. It's in a function
called approxSquareroot. Right here. As its name suggests, this function computes an estimate of the
square root of its input argument x here. There's just one statement in
the body in this while loop. It computes the value
of a variable called y. I'm going to remove this semicolon. You wouldn't ordinarily want to do that,
but I want to see y's value change each
time we iterate through this loop. Let's also go over here and
change the format to long, like that. So we can see more decimals and
ys printed out. Okay, let's calculate
the square root of 2. There. Now, as you can see, it took only one,
two, three iterations. And then it gave us back the answer. And that answer, 1.41, seems like it might
be pretty close to the correct answer. Let's compare it with
the built-in function. [SOUND] Yeah, that's close. Differs by two-millionths. If we test on a larger number,
we'll see it takes a few more iterations. Let's try 200. Now, this time it took one,
two, three, four, five, six iterations, instead of three. Let's see, how close it is this time? Oh, not as close, but still pretty good. That's three-thousandths. Well, let's look at the function itself,
over here a little more carefully. Let's look at the condition here. First thing that happens is the absolute
value of the difference between y square, and x is calculated. Y of course is supposed to
be the square root of x, that's what we're trying
to make it equal to. And if you square the square root of x,
it should be equal to x. So the difference here, ideally,
would be equal to zero. If it's bigger than zero, then we
might want to do a little more work. So, what we do in fact is check to see,
if it's bigger than a thousandth of x. If it's bigger than that, then we
carry out the body of the loop again. And we check this again, and we keep
doing that until the difference between the square of y and x is absolute value, no greater than a thousandth of x,
and then the loop ends. We can talk about this
combination of x and y, that gives us a better estimate of y,
if in a current value of y. But I'm really more
interested in this condition. The key thing to notice here
is there is no loop index. I mean, where is a counter that counts up
the number of times that we go through? Where is a list of
values that it's set to? Where is an increment of n? There is no n. There is no loop index. It's absolutely unneeded, we don't care
how many times we go through this loop. We just care that we go through it, while
this number is bigger than this number. We stop, and that's no longer true,
and declare that we've got a good approximation to
the square root of x and we quit. And if we think we're quitting to soon
to get an answer that's accurate enough. We can increase the accuracy
by changing the one-thousandth of x threshold to something smaller say, make it one ten-millionth Of x. So, it took six iterations for
one-thousandths of x. Now, we've increased the required
accuracy by a factor of 10,000. Wonder how many more iterations
it's going to take now? Better get comfortable. This could take awhile. Wait. One, two, three, four, five,
six, seven iterations. Only one more iteration? Let's see, how accurate this one is, actually compared to
the built-in function here? Three ten-millionths. We went from three-thousandths, and six iterations to three ten-millionths,
and seven iterations. This thing is converging fast. By the way, if you're wondering why
we aren't at one ten-millionth, since we have one ten-millionth here. Remember, that this wild loop condition is
checking the accuracy of the square of y, while down here we're
checking the accuracy of y. Well, let's put that semi colon back in,
now that we've seen how this thing works. And let's see, how accurate we are on
something we know the exact answer to. [INAUDIBLE] Like the square
root of a million. Now, that's pretty accurate. Look at that. It should be 1000. Huh, ten to the minus eleven. Excellent. Let's see the built-in
function try to beat that. Zero. You know, MATLAB,
no body likes a show-off. Okay, our little function may not be
quite as good at calculating square roots as the built-in function. It's a lot better than the built-in
function that's showing you how y loops work, which is after all it's purpose. Let's get back to that by
giving it another input. Let's try to minus 200. Okay, well, it's not doing anything here. Where's our prompt? Well, here's a hint of what's going on,
look over here, you see the word Busy. This means that MATLAB is actually
still working on our function. It hasn't croaked,
it hasn't stopped, it's still going, it's in this wild loop, and
it's going over and over. And it'll go forever because the condition
in this wild loop, will never be false. This will always be greater than that. So we need to stop this thing. Do you remember what we said earlier,
that you should do in a case like this, to stop MATLAB? You could click the little red
button up here, or over here, depending on your operating system,
and stop MATLAB entirely, and start all over again, but
that's not necessary. Ctrl+C will stop this loop. Let's do that. I'll pop-up a keyboard viewer,
so you can see what im doing. And I'll press the Ctrl key on your
keyboard, it might be Ctrl on the key, or it might be Control, and here it's this
little carrot, so I'm going to press that. There you can see I pressed that,
and while I hold that down, I'll press the C key. Okay, and when we did that, everything's
stopped, we got this red message, and we've got our prompt again. The red message is for
once not a slap on the wrist by MATLAB. This message says that the user
stopped it, while it was working. Maybe it's mad because we stopped it. But it tells us where it was,
when it stopped. On line five of the function approx_sqrt,
that's right here. That's the end statement of the loop,
and that's where MATLAB typically stops, when you use Ctrl+C, while it's looping. Let's remove the semicolon here, and run
it again, so we can see things happening. And you can see values of y
streaming out on the screen. It's working hard, but let's go ahead,
and stop it with Ctrl+C. Okay, our function clearly doesn't
work [LAUGH] for this case. The algorithm works only for
non-negative inputs. The square root of a negative
number is a complex number, and we didn't do anything to produce
a complex number in this short function. If you're familiar with complex numbers
you know they have a real part and an imaginary part. MATLAB handles complex numbers with ease,
which is a good thing, because they come up in some
applications in engineering and physics. We're not going to deal with them
except briefly in this course. First, let's see what the built-in square
root function does with minus 200. You see the letter i at the end here? That means imaginary. The square root function is telling us
that square root of minus 200 has a real part that's equal to 0, and an imaginary
part that's equal to, well, all this. We can produce complex numbers, too. There are a couple of ways. Here's one. I just typed an i after the three. And I got a complex number that
has a real part equal to 15 and an imaginary part equal to 3. Here's another way to do it. This time I put 15 plus 3 times i. MATLAB sets the variable i equal
to the square root of minus 1. And you can use it to
make an imaginary number. If you set i equal to say, 7 in
the meantime, and then try this again. Well it uses the 7. If you want to get i back to meaning
the square root of minus 1, clear it. Now let's just look at it. Now you see i is equal to the square root
of minus 1 which is the imaginary 1. That's how you can produce
complex numbers, and it wouldn't be hard to fix our function so that it would return the correct
complex answer for a negative input. But we didn't do that and as a result, the condition in the while loop will
never become false for a negative input. So MATLAB gets stuck in this loop. A loop that'll never end is called an
infinite loop, and it's a feature only of while loops in MATLAB because that's
the only place it can happen. A for-loop can never become an infinite
loop because a loop will always quit when the loop index reaches
the end of its list of values. And there's no way to set up and
infinite list of values, accidentally or on purpose. But since while loops
are susceptible to this problem, we have to be very careful how we set
up the condition of a while loop, and how the variables in the condition are
changed in the body of the while loop, so that eventually the condition
will become false. While we're developing
a program with one or more while loops, it's very common
to make mistakes that cause one of those while loops to get
stuck in an infinite loop. When MATLAB is seemingly
not doing anything, always remember to check the bottom
left corner for a busy message. If you see that,
you know MATLAB is not dead. It's still working on your program. By the way,
some very complex computations can run for a long time,
even on today's fast computers. So whether you're using for-loops or while loops, MATLAB may still take a very
long time to finish your function. In that case, you'll see the busy sign,
and you'll know it's working. But if it's taking too long, you can
always use Ctrl+C to stop the program, whether it's caught in an infinite loop or it's plowing through a calculation
that you just don't want to wait for. [MUSIC] [SOUND] [APPLAUSE]