While Loop in Matlab explained with Example Codes
Table of Contents
Description:
while loop in matlab:- In this tutorial, we are going to introduce you to the while loop which is a loop structure used to repeat a calculation until a prescribed condition has been met, first I will introduce you to the structure of a while loop then I will walk you through an example of a loop pass using a flowchart and finally we will work on example problem together in MATLAB. Let’s get started.
Structure of while loop in Matlab:
A loop is a structure for repeating a calculation or set or number of calculations a predefined number of times. Each repetition of a loop is known as a pass. The while loop is used when the looping process terminates because a prescribed condition has been met unlike in a for loop the number of loop passes is not known in advance.
1 2 3 4 5 |
While logical expression Statement end |
Here’s the typical structure of a while loop and how you would read it while this logical expression is true, the statements are evaluated by the program and when that logical expression is false the loop ends and the program proceeds with any lines of code after the end statement. let’s take a look at an example:
1 2 3 4 5 6 7 |
x=2 ; while x<20 x = 3*x-1 end |
In this case we start by initializing a variable x which has a value of 2 and while x is less than 20 the statements are evaluated which in this case the new value of x is assigned the value of 3 times the current value of x minus 1. Now I would like to make two important notes here when working with while loops first the loop variable must have avalue before the while statement in our case we have assign x = 2 if we did not initialize the variable x then we would have nothing to compare to in this logical expression so for example if there was no x then you could not evaluate the logical expression is x less than20. The second note I would like to make is this the variable must be changed by the statements. So in this case our loop variable is x and it must be changed if it is not we would run into an infinite loop. So for example if x was always equal to 2 then it would also always be less than 20 and this loop would run infinitely.
Now let’s take a look at a flowchart of this example to demonstrate each loop pass.
1 2 3 4 5 6 7 |
x=2 ; while x<20 x = 3*x-1 end |
First, we initialize our variable x which is assigned the value of 2 and we evaluate our logical expression our current value of x is 2 that is less than 20 that statement is true and we begin our first loop pass by evaluating the statement. Our new value of x is assigned the value of 3 times our current value of x minus 1 and our new value of x is now 5. Next, we return to our logical expression, and while this statement is true. We will continue to complete loop passes so our current value of x is 5 that is less than 20. This statement is true and we evaluate our statement again our new value of xis equal to three times our current value of x minus one and our new value of x is now 14. We return to our logical expression and it is still true our current value of x which is 14 is less than 20. This logical expression is true and we begin our third loop pass. Now we evaluate our statement our new value of x is equal to 3 times the old value of x minus 1. Our new value for x now has a value of 41. This time when we evaluate our logical expression our current value of x is actually greater than 20 so this statement is false and our while loop ends. Now let’s take a look at implementing this example problem in MATLAB. Now that we are in Matlab we are going to open a new script file which opens the editor and we’ will begin our program by initializing the variable x is assigned the value of 2. I will put a semicolon here to suppress this statement.
1 2 3 4 5 6 7 |
x=2; while x<20 x=3*x-1 end |
So the value of x is not output to the command window and we are ready to begin our while loop. So we start off with while Matlab will automatically format this text as blue and we begin with our logical expression.So while the current value of x is less than 20 we evaluate the following statement. So I’m going to click enter and Matlab will automatically indent this line for readability and our new value of x is assigned the value of 3 times our current value of x minus 1 and I am not going to add a semicolon. Because I would like to output the value of x for each loop pass and then we finish with the end statement and now we are ready to save and run our program. So i will go up and click save and run give this a file name.
I am going to call it while_loop1 and when I save this, the program will automatically run and what’s interesting is, here is you can see the value of x for each loop pass. So on the first loop pass the new value of x is 5 on this second loop pass the new value of x is 14 and on the third and final loop pass the new value of x is equal to 41. This was the final value for x because once this logical expression was evaluated 41 is not less than 20 that statement is false and the while loop would end.
Example No. 1:
In this example we are going to write a script file to calculate how long it will take to double an initial investment of 1000 thousand dollars in an account with an annual rate of return of 6 percent.
A while loop should be used instead of a for loop because the number of loop passes is not known in advance. In other words we do not know how many years it will take to double our investment. Here is the typical structure of a while loop
1 2 3 4 5 |
while logical expression statement end |
And how we would implement our example problem our logical expression. In this case is while the balance is less than two thousand and that two thousand value is double our initial investment of one thousand dollars so while that logical expression is true.
1 2 3 4 5 6 7 |
while balance<2000 year=year+1; balance=balance*(1+0.06); end |
These statements will be evaluated the first statement advances the year by one. The second statement shows the increase in the account balance accounting for that six percent rate of return and when this logical expression is false which means when the balance meets or exceeds a value of two thousand dollars the while loop will end and the program will proceed with any additional lines of code after the end statement.
Now I would like to make two important notes here. First the loop variable in this case our balance must have a value before the while statement and that’s currently missing and this is because if we don’t know what the balance is then we can’t determine. If it is less than two thousand dollars or not so we need to initialize our balance.
Balance = 1000
We also need to initialize our year the second note I would like to make is the loop variable must be changed by the statements and that’s because if the balance does not change then it has a fixed value of one thousand dollars and thus the balance would always be less than two thousand dollars resulting in an infinite loop.
year=year+1;
Now let’s take a look at a flow chart to visualize.
Each loop pass and how the balance in year changes. our first step is to initialize our variables for the balance and the year then we proceed to our logical expression which states that while the balance is less than two thousand dollars our program will evaluate the statements within the while loop our initial balance of one thousand dollars is less than two thousand dollars that statement is true and we begin our first loop pass we evaluate our two statements within the while loop the year advances by one and our balance updates to account for the six percent rate of return.
Loop pass = 1
Balance = 1060
Year =1
Then we evaluate our logical expression again we take our new balance which currently has a value of one thousand and sixty dollars. Our current balance is less than two thousand dollars that statement is true and we begin our second loop pass again we advance the year by one. Now we are at year two and we accrue interest again and our current account balance is now one thousand one hundred and twenty four dollars after 2 years.
Loop pass = 2
Balance = 1124
Year =2
This process continues for quite a few more loop passes. So i will quickly walk you through the loop passes until we get to number 12. So this is our third loop pass in which our data will become:
Loop pass = 3
Balance = 1191
Year =3
In fourth loop pass;
Loop pass = 4
Balance = 1263
Year =4
In fifth loop pass:
Loop pass = 5
Balance = 1338
Year =5
In sixth loop pass:
Loop pass = 6
Balance = 1419
Year =6
In seventh loop pass:
Loop pass = 7
Balance = 1504
Year =7
In eighth loop pass:
Loop pass = 8
Balance = 1594
Year =8
In ninth loop pass:
Loop pass = 9
Balance = 1690
Year =9
In tenth loop pass:
Loop pass = 10
Balance = 1791
Year =10
In eleventh loop pass:
Loop pass = 11
Balance = 1898
Year =11
This ends up being our 12th and final loop pass so let’s slow down a bit. So on our 12th loop pass we evaluate the year we increment the year by one and we are now in year 12 and once we update our balance accounting for six percent rate of return our new balance is 2012 dollars.
Loop pass = 12
Balance = 2012
Year =12
Now this time when we return to our logical expression our current balance of two thousand and twelve dollars does exceed two thousand dollars.This logical expression is false and our loop now ends. So it took 12 years to double our initial investment of 1000 assuming an annual rate of return of six percent.
Now let’s take a look at solving this problem inside of the Matlab environment. Now that we are in Matlab our first step is going to be to open a new script file.
Now that our editor is open we will begin by initializing our variables for the balance and year. So our balance has an initial value of one thousand dollars and our year is set at year zero
This is because we are going to increment the year by 1. Such that after our first loop pass the year would be 1 and the interest would accrue after we have initialized our variables. We are ready to begin our while loop so we start off with while, Matlab will automatically format this text as blue and next we have our logical expression so while the balance is less than two thousand dollars
balance=1000;
year=0;
while balance<2000
Again we are using two thousand dollars because that would be doubling our initial investment of one thousand dollars.So while the balance is less than two thousand dollars our program will evaluate the following statements:
First we increment the year so our new value of the year is assigned the value of our current value for the year plus one to increment the year by one with each loop pass and I am going to add a semicolon here to suppress the output and click enter
Year=year+1;
We will begin our next line of code for our balance. So our balance is assigned the value of the current balance which on our first loop pass is one thousand dollars plus interest and in this case we are assuming a six percent rate of return and i will suppress this statement.
So it is not output to the command window during each loop pass. Now I will end the while loop and as soon as our logical expression evaluates as false the while loop will end and what we want to do is to display our ending balance and how many years that it took to reach that balance. So I am going to display the year and display the balance so we will remove the semicolon from year and balance in order to display it in the command window.
Then we will go up to our editor tab and click save and run and give this a file name I am going to use while_loop2 and when I click save the program will run.
In this case we can see that our final value for the year is twelve and our final balance is two thousand and twelve dollars.
Now when we get to year 12 our balance exceeds our goal of double or in this initial investment of two thousand dollars and our while loop ends.