3.4.1: for Loop Supplemental Material
- Page ID
- 84377
By Carey A. Smith
Structure of a for loop
Every for loop must start with the key word "for" followed by the loop index and its values.
Then the body of the for loop is whatever code your want.
Then the keyword "end" specifies the end of the loop code.
This is a simple example:
for kk = 1:4
x = cos(kk*pi/16);
y = sin(kk*pi/16);
end
For good style, vertically align the "for" and "end". Indent the body of the for loop.
You may use the index (kk in this example) in the calculations, as shown in this example. But never modify the loop index inside the for loop. MATLAB will increment the index automatically.
Watch these videos for additional instruction on for loops:
Video: Looping structures in MATLAB: Basic FOR loops, Robert Talbert
https://www.youtube.com/watch?v=5a3bpKuBpgo
Video: MATLAB For Loop Tutorial, Ilya Mikhelson
Here are 2 more examples of for loops:
Figure \(\PageIndex{i}\): Factorial for loop flowchart
Factorial Example for loop
The factorial of a number N in algebra is defined as:
N! = 1*2*3*...*N
This can be computed in MATLAB/Octave using a for loop using the logic described in accompanying figure.
Solution
The MATLAB code for this is:
% Input (precondition): N = integer >= 2
% Output: FN
FN = 1; % Starting value
for k = 2:N % k=index, kstart : to kend
FN = FN*k
end
Compute x^n these 2 ways:
1a. Set x = 2
1b. Set n = 7
1c. Compute a = x^n.
2a. Set result = 1
2b. Code a for loop that multiplies result by x, n times.
2c. Use this line inside the for loop:
result = result*x
- Answer
-
x = 2 % Initialze x
n = 7 % Initialze n (the power)
result = 1 % Initialze the result
for k=1:n
result = result*x
end
.