How to Store Output Values from All Iterations of a For Loop in MATLAB | Preallocation Part 1

Hey guys! This is a video in my MATLAB tutorial series. In this video, I am going to demonstrate how to store values from all iterations of a for loop in a single array. The previous video was an introduction to using for loops and plotting in for loops. So, if you need a refresher on the essentials of for loops, that video will be linked in the description below. In this video, I am going to focus on preallocation to store the results from all iterations of a for loop in a single array. Without further ado, let’s get to it.

            Last time, I mentioned that when you use a for loop, the only value stored in the workspace is the very values from the last iteration. For example, let’s create a very simple for loop. First, let’s write clear here to clear anything in the workspace followed by clc to clear anything in the command window. Then, I am going to create a vector that I am going to assign the name x. I’ll say x = linspace(0,10,11). Let’s suppress the output with a semicolon. I want to run this to see what my x vector looks like to make sure that it’s what I wanted it to be. Just a reminder that the first number (zero) is the starting value for the vector, the second value (10) is the ending value of the vector, and the third value (11) is the number of elements that the vector will have. Having 11 elements will allow us to have an increment of 1. Let’s just run this to see what it looks like. Remember to save your script first. I’ll save it as preallocation_for_loop. You can either click run or the hotkey for running a script is ctrl+enter. After running it, the vector won’t appear in the command window since it’s suppressed as a result of the semicolon. We can click the variable name in the workspace and we can see that it is indeed a vector with 1 row and 11 columns. It starts at 0 and ends at 10. The increment is 1, as expected. Even though we already know that the number of elements. I am still going to use the length command to set a variable equal to the length of the vector, which is 11. This is ensure that the subsequent portion of my code won’t change in the event that I decide to change the number of elements in the x vector. I’ll write n = length(x). The length command returns the largest array dimension. Since x is a 1 by 11 vector, the length of x will be 11.

            We are going to create a for loop that goes through n iterations. Let’s write out the code and then discuss what’s going on. The for loop is going to look as follows:

for i = 1:n

    y = 3*x(i);

end

First, we are starting the for loop by typing in for. Then i is the variable name assigned to the loop index vector. In the workspace, we can quickly see what the loop index vector looks like. It goes from 1 to n. We already know that n is 11. When we copy paste the loop index vector in the command window, we can see that the vector starts at one, which corresponds to the first iteration, and ends at 11, which corresponds to the last iteration. Recall from the previous video on the basics of for loops that MATLAB indices must positive integers, and the lowest index value is 1. The code inside the for loop takes the ith value in the vector x and multiplies it by 3 and the output is assigned the variable name y. So, for the first iteration of the for loop, MATLAB will take the first element in the x vector, which is 0 and multiply that by 3. Then, for the second iteration, i will equal two. Thus, MATLAB will take the 2nd element from the x vector which will be one and multiply it by 3. It will keep doing a similar procedure for the remaining iterations. The semicolon is there to suppress the output from appearing in the command window. Remember that you have to close off the for loop with end. The way I have the code written right now, MATLAB should only store the y value from the last iteration in the workspace. So, I am expecting to see 3*10, which is 30, in the workspace for the y value. Let’s run it.

            Once we run the code, as expected, you’ll see in the workspace that only 30 shows up as equal to y. Even if you click on it, you cannot see the values of y from the previous iterations. If I get rid of the semicolon from inside the code and run it, I can visually see the results from all the iterations, but this isn’t very useful for any future calculations.

            The first thing we can try is to write y(i). Let’s see what happens now. Let’s run the script. Notice in the workspace that y is now a 1 by 11 vector instead of simply being a number. If we click on the variable name y from the workspace, we can see all the output values of y from all 11 iterations for the for loop. After the first pass in the for loop, the value of y is 0, which is 0 times 3. For the 2nd iteration, it’s 3, which is 1 times 3, and so on for all other iterations. Let’s close the window that has the y vector. There is, however, an inefficiency with this method. The scroll bar has turned yellow. If you hover over the yellow next to the code in the code inside the for loop, you will see a message that reads y appears to change size after every iteration. The second warning, we can ignore since I intentionally omitted the semicolon for demonstration purposes. Now, why does it say that the variable y appears to change size. Let’s take a look at the command window to understand what’s going on. We can see each pass or iteration of the for loop in the command window since we haven’t suppressed it with a semicolon. After the first iteration, y equals 0. So, the dimension of y would be 1 by 1 since it only needs to store one value. However, after the second iteration, notice that we have the value from the first iteration, which is 0, but we also have the new value for the second iteration, which is 3. Thus, the dimension for y is a 1 by 2 vector. Likewise, after the third iteration, y will be a 1 by 3 vector since it also needs to store the y value from the third iteration in addition to the values from the previous 2 iterations. This process will keep going on until the for-loop iterations are complete. This is what the warning message meant that the dimension of y is changing.

            In this simple, case there is no problem with the execution of the code leaving it as is, but it’s a good scope to demonstrate the concept of preallocation, which we can apply to longer and more complex codes. What we’re going to do is create an array, in this case, we need a simple 1 by 11 vector, that has the dimension we need for our output vector. So, before the for loop, we’ll say y = zeros(1,n). What this is doing is creating a vector that has the dimension 1 by n, where n we already know to be 11. This array is called y. As the for loop iterates MATLAB will replace the zeros with the values from that iteration in the respective location of the preallocated array. Let’s just type in zeros(1,11) in the command window to see what the vector looks like first. Let’s press enter. You can see it’s a row vector will zeros in every location.

            Now, I am going to include a 3-second pause after each iteration and still leave out the semicolon from the code inside the for loop so we can visualize the zeros being replaced from the preallocated vector.

clear

clc

x = linspace(0,10,11);

n = length(x);

y = zeros(1,n)

for i = 1:n

    y(i) = 3*x(i)

    pause(3)

end

Keep looking at the command window and you will see that the zeros get replaced by values of y after each pass of the for loop. Let’s run the code. Now, let’s scroll through the command window to fully take in what we were looking at as the values updated. Let’s start from the top. First, we started with an array that comprised 0’s. After the first pass, the value of y in the first location was replaced with 0 again so you can’t really see a difference there. However, after the second iteration of the for loop, you can clearly see that the 2nd value has been replaced by a 3. After the 3rd pass, the 3rd value has been replaced by a 6 and so on. You can see this happening until all iterations of the for loop has been complete. We can also access, the y vector in the workspace by double clicking. Now, we can go back to the code and take out the pause and add in semicolons to make this cleaner. Let’s run this again. This time, nothing shows up in the command window because it’s suppressed but we can still access the y vector from the workspace. Also, the scroll bar is green. So, MATLAB hasn’t found any warnings. That’s great news!

            We can even plot y versus x, if we wanted to. After the for loop, we’ll type in:

figure

plot(x,y)

xlabel(‘x’)

ylabel(‘y’)

Once we run it, we can see the plot.

            Now, what would have happened if I had said y = zeros(n,1) instead of 1, n. Let’s try it. Once we run it and open the y vector from the workspace, we can see that it is a column vector. This is expected since the dimensions of an array are given as row by column. We just told MATLAB that the dimension for this zeros array is 11 by 1. So, 1 column and 11 rows. So, just be careful of which way you want the output stored based on what you are asking the rest of your code to do.

            Another thing to look at might be what happens when we say y = zeros(n). Let’s do it and then run it. In the workspace, you can see that y has the dimensions n by n, or 11 by 11. When you don’t specify the number of rows and columns and put a single value, MATLAB will take it to be a square array. So, just be careful in deciding what you need.

            Also, remember this y(i). Let’s see what happens when we forget to include the loop index after the y in parentheses. Let’s change the zeros array back to y = zeros(1,n). Let’s take the i out. When we do that, the y values don’t replace the values in the zeros array like before. If you look at the workspace, only the last value is stored again.

            That’s it for this video. In the next video, we are going to see a continuation of preallocation but with the dot operator. That would be when you have two variables that are changing. For every iteration of the for loop, we’ll set one of the variables to be a fixed number for the iteration while the other variable goes through multiple values. The results will be stored in a matrix that has been preallocated. It will probably be easier when seeing it.

            I hope this video has been helpful in some way. I hope you guys are staying safe and healthy. If you haven’t already, please SUBCRIBE!!! Check other videos on my channel, especially the MATLAB tutorial series as well as the graphing and scientific calculator tutorial series. Also, check out the math videos. Until next time, take care guys!