In today’s lesson, we’re going to cover the following topics:
1. Control Flow Structures
2. For Loops
3. Nested For Loops
VIDEO COMING SOON
Control Flow Structures
Within MATLAB, we are able to create codes that will execute a decision for us – “if this happens, then do this” kind of thing. This is called control flow logic. MATLAB has 4 of these – for loops and while loops, as well as two conditional statements – if-else and switchcase. Each of these have their own lesson plan, and today we will focus on for loops.
Some students ask about the difference between a for loop and a while loop – check out the first couple paragraphs in this lesson on while loops if you are also confused about this!
For Loops
For loops are used to execute a specific command a certain number of times. The structure of the for loop is the following:
You will replace the word variable with a variable of your choice, replace the word expression with whatever you want that variable to equal in order to run the loop, and replace the words code_to_execute with the code you want MATLAB to run when that condition is satisfied.
Let’s try an example so you can understand how this works. Here’s the question we will solve:
I want to make a code that will multiply each number by 5 for values of 1 through 10.
The first step to thinking through this problem is to understand that we need to run through values of 1 to 10. We won’t be manually entering these values and running the code 10 times – how would we do this when we have, say, 100 values? Using a loop is much more efficient to automatically run through the code with each value. To do this, we need to create a vector of numbers from 1 to 10.
This will be [1 2 3 4 5 6 7 8 9 10], or you can use the colon operator as discussed in a previous lesson, which would be 1:1:10. This will go from 1 to 10, in steps of 1. It’s easier to use the colon operator to create a vector when we have data sets that may be larger than just 1 to 10.
The next step is to make a loop, and we can use a for loop in this case because the condition will execute for values of 1 to 10, using the vector we made. A for loop starts with the word for, and ends with the word end. In between these two words you will have code. You will then have to determine – within this loop, what code needs to be executed?
The question asks that we multiply each number from 1 to 10 by the number 5. So let’s say we want to set the vector [1 2 3 4 5 6 7 8 9 10] equal to the variable x. Then within the for loop, we can do 5*x, which will multiply each number in the vector by 5.
Let’s put this together in a code. When you hit enter to type each next line of code, it automatically staggers them. See how the 5*x line is farther in than the for and end statements, which turn blue.
Now when you save the file and hit the green Run button at the top, this is what comes up in the Command Window.
How do we know if our answer is correct? We can manually do 5 multiplied by 1, then 5 multiplied by 2, and so on until we do 5 multiplied by 10. This is tedious though, but it can be used to check your answer by hand. The code we created has just given us the answers to this! So you should have 10 numbers in the Command Window when the code is executed, which is what we have.
Let’s try another example. This time I would like to calculate the factorial of a number. The answer to this code ends up using two for loops rather than one. There is a loop within a loop, and this is called a nested loop.
Nested For Loops
A loop can be a nested for loop if there are two for loops within one another, a nested while loop if there are two while loops within one another, or just a nested loop if there is one for and one while loop within each other.
Refresher: Taking the factorial of a number takes all the previous values, including that number, and multiplies them together. So the factorial of 3 will be expressed as 3! and will do 3 * 2 * 1 to give 6. How do we create a loop to find the factorial of numbers 1 through 10?
Thinking through this question, it asks us to work through the values 1 to 10, just like the previous example. So we should create a vector from 1 to 10, and let’s call it x. This will be x=1:1:10 or x=[1 2 3 4 5 6 7 8 9 10] as I discussed in the previous example again.
Now this is the condition for the for loop to execute, but what about the code within the loop? When we take the factorial of each number, it needs to be multiplied by every previous value within that vector.
It is a little easier to start with one loop rather than a nested loop, so let’s first try creating a loop to find the factorial with just one given number, rather than cycling from 1 to 10. With this, we can try to find the factorial of 5.
1) The first step is to set a variable equal to 5, let’s say n = 5.
2) Next we need to initialize the product – because factorials are multiplying values together, the product of these values needs to be initialized – set to one value that it will begin with. I won’t set it to 0, because if we multiply by 0 then we will keep getting 0.
3) Now we will create the for loop and an end statement, and put code within the loop.
4) The for loop condition in this case will be from 1:n. It could be defined from 1:5 instead, but if you change the value of n then you’ll have to change the numbers everywhere in the code. It is easier to just use a variable such as n and then define the number at the beginning, depending on what you’d like. For us that was n = 5.
5) As for the code in the loop, we need loop through values from 1 to 5 and multiply each one in order to find the factorial of 5. This means doing 1*2*3*4*5 and will equal 120 as the final answer (so you can check if you got it right).
This is where we take the final answer (aka the product of all the values we are multiplying together) that we initialized earlier, and multiply it by all the values from 1 to 5. This will make the product equal to the initial product (which was 1) multiplied by 1* 2* 3* 4* 5. Yes, multiplying by an initialized value of 1 does not seem necessary, but this is how to get the product of all the previous numbers equal to the factorial.
This is what we get:
This is what the Command Window gives when the code is run, and the answer is circled in red. It is the correct answer for the factorial of 5, aka 5! It is 5 * 4 * 3 * 2 * 1 = 120: But this is not what the question asked.
We chose a value of 5 to find the factorial, but how can we replace this with a vector from 1 to 10 so we don’t manually find the factorial of each value separately? Now that we have this working factorial code, let’s work through this last part.
Changes made to the code above:
(a) Instead of using n = 5, I will replace it with the vector n = 1:1:10, or you can use n = [1 2 3 4 5 6 7 8 9 10].
(b) This won’t work if just type in the vector like we did with n = 5. We need to use a for loop so MATLAB goes through each value in the vector and executes the code for each one. So we add a for before this vector, and add an extra end statement to the end of the code – every time you add a for statement, there has to be a corresponding end.
Putting these all together looks like this:
Running the code looks like this in the Command Window. All of these values are the factorials for the numbers 1 to 10:
How can we get MATLAB to print these values neatly? We will use fprintf to format these – click here if you missed that lesson. We can use this to create a list that shows all the factorials with their corresponding numbers. We just want to set it to look like this: factorial = number.
Using fprintf, I have added a new line to the code we used completed (highlighted in yellow). It should be added outside of the first for loop, otherwise it will execute this statement 10 times, one for each time it loops. If the code is put outside both loops, it will only show the answer to the last loop, which is the factorial of 10. Therefore, the placement of the fprintf statement must be between the two end statements like I have put below:
This is what the output looks like when the code is run: