The first MATLAB loop that we will learn about are for loops. For loops allow us to repeat code a specified number of times. Let's take a look.
matlab
for i = 1:3
disp(i);
end
% output:
% 1
% 2
% 3
We start out by defining a variable to use to contain the current count that we are in and then we define the interval at which 'i' will increment. So, in this example, 'i' will start at 1, the code within the for loop with run, then 'i' will increment by 1 to then be 2, the code will run again, and then it will increment by 1 again and then run the code again with 'i' equaling 3. That is why the output is 1, 2, and 3 separately.
We can also define variables that do not increment by one. Let's learn something new!
matlab
for j = 1:2:5
disp(j);
end
% output:
% 1
% 3
% 5
We can use the notation start:step:end to create a 1D array of variables that starts at the first value and increases by the second value until the third value is reached. So in this example, we are starting at 1, incrementing by 2, and then stopping at 5.
This is a handy trick for us that we can use for many different exciting things to come!