Skip to main content

Section 15.2 MATLAB for-end Loops

From our flowchart in figure 15.1.4 above, we can see that we are going to use a for loop. In the thinking algorithmically chapter we learned how and when to use a for loop. Now we just need to see how to program this type of loop into MATLAB.
Recall that for loops execute a pre-determined number of times. Generically, in MATLAB, they are programmed as follows:
for index_variable = first_pass : increment : last_pass
<code to be executed during the loop>
for-end Loop Important Details
  • for loops require 2 numbers to be defined: first_pass and last_pass.
  • The number increment is optional. If it is omitted, the increment will default to 1.
  • MATLAB will modify the index_variable by the increment amount specified at the start of each pass through the loop.
  • The loop is completed when the index_variable value is greater than or equal to the last_pass number. In the flowchart below this is what is meant by the true/false condition on the for loop diamond box.
  • The index_variable persists in the workspace after the loop is completed. That means you can check it to make sure that it worked the way that you expected it to.
  • The index_variable can either be used in calculations inside of the loop if necessary or desired.
  • Similarly to decision structures, the for and end lines of code should not end in a ;
  • The first_pass, increment, and last_pass variables can actually contain functions or mathematical statements as long as they evaluate to a number.
  • For example, consider an array named gamma is defined in the workspace: for kappa = 1:length(gamma) is valid because when the function length(gamma) is evaluated by MATLAB, an integer is returned. In this case, the increment is equal to 1 because a specific increment was omitted. So if length(gamma) = 5, this loop would run 5 times. The flowchart for the generic for loop is shown below in figure 15.2.4.
Figure 15.2.1. Generic MATLAB for loop flowchart. The variable names are a little different than in the generic code example above (e.g. index_variable was shortened to index, etc) to preserve space but the logic is the same.
As an example, consider the example code below in figure 15.2.2. This may look complicated but in practice, it looks more complicated than it really is. See if you can follow the logic presented in the figure. It would also help to try and β€œfollow along” on your own on a sheet of paper. See if you can follow the value variable throughout the looping process.
Figure 15.2.2. An example of a for loop execution process. You can confirm this by executing the sample code in MATLAB on your own!
Stop and Think
You need to spend some time reviewing figures 15.2.1 and 15.2.2 to really understand how these loops work. If this explanation is confusing to you, try taking a break from this text, and looking at someone else’s explanation. The important thing is that you understand what for loops are and how to use them.
If you search for β€œfor loops” on YouTube you can find hundreds of videos of people explaining these looping structures. Here is one such video.
Figure 15.2.3. Youtube Video on for Loops

Checkpoint 15.2.4. For Loops.

What are three thing you learned about for loops from an outside resource? How will this help you when writing and executing code?
Think about a time where you might want to use a for loop. How has this new information helped you for future coding projects? How does this built-in function differ from the other built in function(s) you have learned?
for-end Key Concept #1 - Loop Executed a Specified Number of Times
In the example loop: for z = 1:2:5 we can see that this loop will only run a total of three times. The first time through the loop z = 1, the second time through, z = 3, and the last time through, z = 5. The key to remember is that the for-end loop will only run a specified number of times that is pre-determined based on the first line of the loop.
Figure 15.2.5. The loop will only run a specified number of times. Unlike the roll of the dice, this is predetermined by the programmer.
When designing your programs, it is important to think about how to define your index_variable and what values to specify for it so that you can control the number of passes through the loop.
for-end Key Concept #2 - Follow the Variables
In addition to predicting the number of times loop code will execute you should also be able to β€œfollow the variables” through the execution of the code. Following the variables is important so that you can troubleshoot errors in your loops and predict what values should be generated by your loop. An example of following the variables was shown in figure 15.2.2 above. The idea is that you can sketch what should happen when the code has been run.

Checkpoint 15.2.6. FOR Loop Variables.

Consider the code:
sneetches = 0;
for stars = 0:5:25
    sneetches = sneetches + stars;
end
What is the value of the sneetches variable when this code is run?
  • 15
  • Incorrect. Try tracking the value of sneetches through each iteration of the loop.
  • 30
  • Incorrect. Be sure to include all values generated by the loop.
  • 0
  • Incorrect. Although sneetches starts at 0, its value changes during the loop.
  • 5
  • Incorrect. The loop executes multiple times.
  • 100
  • Incorrect. The sum is smaller than 100.
  • 75
  • Correct. The values of stars are 0, 5, 10, 15, 20, and 25. Their sum is 75.
  • 50
  • Incorrect. Try adding all of the values generated by the loop.
for-endKey Concept #3 - Analyze Arrays
The final important thing to consider when learning about for-end loops is that they can be used to analyze and build arrays. For example, let’s consider that we have an array defined in the workspace as follows:
man_bear_pig = [1, 1, 2, 1, 4, 2, 4, 5];
As an example, let’s say that we want to add all the values in this array (you can use the built-in sum() function for this but let’s consider how to do this using loops as an example). We can use a for loop to cycle through all of the values in the array! This code will accomplish this:

Example 15.2.7. man_bear_pig.

Here is an interactive code box that functions identically to the MATLAB command window.
The key here is to notice how the for loop was used to loop through every value of the array man_bear_pig. Since the increment is 1, we can use the index variable to access the data within the array. This is a common application of for loops and one that you need to have in your tool belt to be a successful programmer.

Checkpoint 15.2.8. Loop Iterations.

Consider the 3rd pass through this loop. What is the value stored in man_bear_pig(index) on the 3rd pass through the loop?
  • 7
  • Incorrect. Follow the value of index through each iteration and determine which array element is accessed on the third pass.
  • 1
  • Incorrect. Be careful not to confuse the value of index with the value stored in the array.
  • 4
  • Correct. On the third pass through the loop, man_bear_pig(index) contains the value 4.
  • 5
  • Incorrect. Check which element of the array corresponds to the third iteration.
  • 20
  • Incorrect. This value is not stored in man_bear_pig(index) during the third pass through the loop.
You have attempted of activities on this page.