for
For loop is useful for executing many iterations of a statement.
Syntax
for X = expression
statement
end
Inputs
- x
- Anything that can be logically tested.
- expression
- Anything that has a valid array or a valid expression comprised of the initial value, step (optional), and end value.
Outputs
- statement
- Executed if the expression in the for condition is true.
Examples
sum=0
for j=1:10
sum = sum + j
end
sum
sum = 0
sum = 1
sum = 3
sum = 6
sum = 10
sum = 15
sum = 21
sum = 28
sum = 36
sum = 45
sum = 55
sum = 55
for j = [-1,0;3,-2]
disp(j)
end
[Matrix] 2 x 1
-1
3
[Matrix] 2 x 1
0
-2
expr = [-1:0.5:2];
mult = 1;
for j = expr
mult = mult .* expr;
end
mult
mult = [Matrix] 1 x 7
-1.00000 -0.00781 0.00000 0.00781 1.00000 17.08594 128.00000
val = 10;
for j = 5:-1:1
val = val - j
end
val = 5
val = 1
val = -2
val = -4
val = -5