For-loops in MATLAB

Mike X Cohen
A free video tutorial from Mike X Cohen
Neuroscientist, writer, professor
4.6 instructor rating • 20 courses • 106,403 students

Learn more from the full course

MATLAB onramp 2020: coding, concepts, confidence, and style

Learn the key MATLAB programming skills that separate experts from novices: debugging, functions, and visualization

10:19:56 of on-demand video • Updated February 2021

  • Introduction to MATLAB
  • How to write scripts and functions
  • Visualize data in 2D and 3D
  • Control statements
  • Develop your programming style
  • Think like a programmer
  • Find and fix bugs!
  • Learn the most common coding mistakes and how to avoid them
  • Strategies for planning and organizing your code
English [Auto] This is a pretty exciting video. I'm going to show you all about for loops how to create for loops. This is not about Froot Loops that weird sugary cereal. That's probably pretty unhealthy for you. This is for loops. So the idea of a for loop is to repeat a set of statements a set of code multiple times some number of times that you get to specify. And I'm also going to show you in this video how to create what's called nested control statements that is taking one control statement and embedding it inside another control statement so let's start with a simple example here. So here we say for an end again you see these reserved Matlab keywords. And here I have some variable that I set equal to some number or sequence in this case it's a sequence so the conditional part of this loop is this vector that tells Matlab the number of times to repeat inside the loop and also the values of the looping variable. So this is often called the looping variable or sometimes the looping index. So here I specify that the looping variable should go from 1 to 10. So that means that Matlab is going to run all the code in between the fourth statement and the end statement on this case all the code is just one line but of course in practice you might have many many lines of code in here. So all of this code is going to be run 10 times and each time Matlab iterate through running this code it's going to change the value of this variable to according to these numbers that I specified here. So this is maybe a little bit confusing at first because if you would just run this code here that would actually produce a vector. So now we have this variable counting variable is a vector of integers 1 through 10. However I'm going to run through this for loop and display this is the disk function for displaying something to the command window. It's going to display the value of this looping variable. Each iteration each time it goes through. So let's run all of this and now you see that at each iteration the variable counting variable is not equal to an entire vector. Instead it's only equal to one value at a time. And that keeps incrementing. So it goes one two three four and so on. Now this also means that you do not need to explicitly update the value of this counting variable. So for example you do not need say counting variable equals counting counting variable plus one that's a little different from some other programming languages where you have to explicitly update the counting variables. That is not necessary in Matlab. Matlab will do that for you. Now in this next example I'm just showing it while I'm showing you two things One is that you don't need to set these looping index variables to be increasing in just integers in unit integers. They can also increase by 2. They can basically be almost whatever you want although towards the end of this video I'm going to show you a common mistake that people make with for loops. So that was one thing I want to show you the other thing I want to illustrate to you in this example is that this looping index can be used in mathematical expression. So here I am saying that maybe I'll just run this code and then we can you'll see exactly what it says. OK. So this is the first iteration value times two divided by three and added seven is seven point six six seven. So you see here that I'm using the looping variable I as a number in a mathematical expression. Now you can also see that this is incorrect. This says once but this should say first. So this really should be SD. And here we have three three if this should really be third. And so this should be R D. And by the time we get to here 5th 7th 9th this is starting to be correct. So that means that if you want to actually have some code that looks like this where you're printing out the I's iteration you're gonna need to do something else more than just this one line of code you're not going to need to adapt the code somehow to say you know if the eye is equal to 1 then this should say s.t. and actually that is exactly the hint for where we are going with this next example. So this is showing you an example of nesting control statements or embedding multiple control statements. So you already know about if then statements and now you know about for loops. And so here what we are doing is just combining these two concepts into one little paragraph of code so we loop over 10 iterations. So all of this code gets run in 10 times and let's see what this code is doing. So this is saying if my name I know my is this looping index variable here Comma 2 equals zero so this is gonna be our conditional. This is a boolean statement it's either true or false. Now what does this mean. So this is a mod function. It's short for the modulus and the modulus is more commonly called the remainder. It's the remainder after division. So what the mod function does is divide the first input by the second input and return whatever is the remainder of that division. And so this is actually one way to determine the parody of a number parody of a number is just whether an integer is is even or odd so we say the Modulus of this looping index here which goes from 1 to 10. So this number divided by two. And what is the remainder. Well if the remainder of a number after dividing by two is zero then it's an even number. And if the remainder is not zero. So it's gonna be 1 then it is an odd number. And that's what we are basically testing here. So we loop through all of these and then we test whether the number num eye is even or odd. And then we print out that information. So the number one is odd and that's the way the news goes apparently. The number two is even. And so on up to 10. Now there's another concept about programming style that I would like to point out in this particular example. It is common to have looping indices use a loop these looping variables that to end in the letter I. And that's because that is that can act as like a key term for you to notice that the variable that ends with IE is going to be the looping index. That's the eye is for index. So you can have your your looping index variable be something meaningful like num for number and then eye for index. That's useful because then when you see the variable throughout the rest of this year you know that it's going to end in I or you see that it ends and I. And then you know that that corresponds to a looping index. OK. Then I want to show you another embedding of multiple for loops here. So here we embedded an if statement in a for loop here I'm embedding a for loop inside another for loop. So what is happening inside this for loop. Well we are looping over for I so variable I equals 1 through 5 and then we're looping over variable j for three through seven and then we say that the product matrix of this variable matrix and then the IRS row and the J ith column is equal to I times J. So the row index times the column index. So this illustrates multiple concepts here. One it illustrates that we can use these looping indices both as indices into a matrix or vector and also for mathematical expressions here I'm also illustrating the concept that for loop a looping index variables are often called ie for the first one and then the next one will be called J. Now this arguably isn't such a great set of variable names. You remember I talked about variable naming conventions and guidelines at the end of the section on variables and I said you should avoid using variables that are single letters. So in this case I think it's permissible because the for loop is actually quite small so it's not hard to see where the eye and the J correspond to. If you had dozens or hundreds of lines of code inside these embedded for loops then it would probably be better to use specific names. Maybe you could call this row I and call J. For example case. Let me get rid of these things and then there's a final concept to illustrate with this particular example. And that is that this variable actually doesn't exist. I'm gonna just select this text and press evaluate selection. Matlab says unrecognized function or variable product matrix so I haven't yet created a variable or a matrix in this case called Product matrix but I'm just creating it here on the fly. So let's run this code and see what we get. So the product matrix product matrix turns out to be. Here we have all of the. So these values here the row index times the column index and what you also notice is that we start variable j which corresponds to the columns here. We started at 3 9 at 1 and so Matlab automatically fills in any missing values with zeros. That's important to know. Matlab will fill in missing values with zeros so we create this matrix on the fly on the other hand. Matlab does actually giving us this warning message here. So it says it says the variable assigned to the value assigned to product matrix might be unused. OK. So that's actually Matlab is just telling us that you know we're creating is variable and not using it anywhere else in the code. The error message that I actually want to show you is the second one which reads the variable product matrix appears to change in size on every loop iteration. Consider reallocating for speed. So Matlab doesn't like that we are creating this matrix to be filled in on the fly. So as this as we go through these two embedded for loops this matrix gets larger and larger. Instead what we should be doing is something called initializing. So we are going to initialize this matrix and it's common to initialize with zeros. So I'm going to use this function zeros here I specify the number of inputs corresponds to the number of dimensions of the matrix and the value at each hour in each input corresponds to the size the number of elements along that dimension. So here I am pre allocating the Matrix the size of the matrix in MATLAB memory so I specify that the number of rows should be five number of columns to be seven and then here I set this variable to be equal to all zeros and then this is basically the same loop as I had earlier. And then there's another nice aspect of coding style that you can see in this example and that is that the end statements have a comment afterwards and I say end J loop because I call this J. And here I say and I loop and I call this I loop here because I call the looping variable the looping index here I. So this is another example where you know this little toy example where we only have 5 lines of code it's a little ridiculous to explicitly say that this is the end of the J loop it's pretty obvious here but you can imagine that if you have hundreds of lines of code here so lots of code in here and maybe lots of code in here and let's say there is another couple dozen lines of code here. Now it starts to get pretty useful to see where what this end statement is actually corresponding to. So you look at this and say OK this is the end of the J loop and this is a code that needs to get run after we finish this J loop. So this is good programming style here now there's one final thing I want to mention in this video and that is a common mistake a mistake that people commonly make when using looping for loops and looping indices that don't necessarily start at 1:00 or that don't go in integers. So here it looks like we are just creating a vector and we want this vector to go to be populated with numbers that go from minus three to plus three. Now of course in this example you don't really need a for loop to create a vector that goes from minus three to plus three. But I want to illustrate the mistake that is often made and that mistake is that we are using this looping variable here I as an index and as a as an as a number. Now the problem here is that we're going to start by requesting the index of minus three and there is no index of minus three indices must start at 1 with the first element. So if you like I encourage you to pause the video and come up with a solution to this problem to get this code to work while still using a for loop. So as I mentioned you know you don't really need a for loop here but keep the for loop and just change the code so that it works as expected. OK. So one way to solve this problem is to set the this this vector minus three two plus three as some other variable. I'll even call this other variable like this. So I say an other variable goes from minus three to plus three. And now what should we set i2. Well because we're using AI as a looping index here we actually want AI to be integers that start at 1 and go up to the total number of numbers the number of elements in other variable. So I'm going to say for I equals 1 2. Remember I introduced you to this function length so other length of other variable. Now here we are initializing the vector and here I is going to go from 1 to 7. And then we still get our correct result a Vec and this is going to go whoops I made a mistake here. This is actually incorrect. What I really wanted to do the way this should work is say other variable variable. I'm sure you noticed that and we're screaming at your computer screen for me to do the right thing. So now this is pretty interesting. We are indexing two different variables in two different ways. Here I'm indexing the variable that I want to assign this value into. And here I am indexing this vector here where I have the data vector that I want to specify. And now it should be correct. All right. So now we get this variable a Vec goes from minus three up to plus three. Very nice. So we covered a lot of really great material in this video. I hope you found it useful and fruitful. So we covered for loops. That was the main thing. I also talked about several different aspects of programming style to make sure that you're for loops look good and are sensibly written and easy to read. And I also introduced you to the concept of nested control statements basically where you take one control statement and embed it inside another control statement in the next video. I'm going to talk about while loops which are pretty similar to for loops but they differ in a subtle but important way. So I will see you soon.