MATLAB can implement common loops such as for loops.
- MATLAB has the ability to set up loops like we do in other programming languages, so let's check out a for loop. Let's go ahead and clear our workspace and our screen. Let's close our switch, and let's create a new file here. New file, new script, and we'll call it "Let's Loop." Open that up. So first let's check out a for loop. For loop. So for loops in MATLAB are really simple to use. We just have to set up our index as a vector.
So we do it like this: we say, "for," and we'll use "i" as our index, and then we just use our vector notation, so we'll say, for instance, one through ten. So that'll step i from one to ten in steps of one and we'll just do something simple here, we'll display "i" and "end." I'll go ahead and drag my command window up here so we can see everything, and let's go ahead and run it. So there we go.
We got a simple for loop, stepping through that vector, grabbing all the values of i and displaying them. We can fancier though, if we want. And let's go ahead now, and instead of stepping from one to ten in steps of one, let's step from one to ten in steps of two. So we do that by adding a two in between here. So we're essentially telling MATLAB, "Start at one, go to ten, and do that in steps of two." So if we run this one, we see that happens, we start at one and go in steps of two up to nine.
What I find is often very useful is to set up these parameters for i with variables. So for instance maybe somewhere else in our script we're calculating the end number. And say that's 25. And we also might have a variable step size at some point. So let's do "step" and we'll set that equal to five. Then in our for loop down here, we can use those variables for our index. So we'll start at, let's say this time we'll start at zero. Zero, we'll go in steps of "step," and we'll finish up at "n." So let's come down here to this screen one more time and let's watch this one run.
So there we go. We start at zero, we step in steps of five up to 25. Setting up your for loops like this can be really useful when you're calculating things on the fly.
Released
4/16/2018- Creating MATLAB variables
- Working with matrix and scalar operations
- Using if statements and loops
- Creating functions
- Importing data
- Building basic plots and 3D plots
- Working with images
- Creating Simulink models
Share this video
Embed this video
Video: For loops