
Flow Control
Loop Control – for, while, continue, break
This section covers those MATLAB functions that provide control over
program loops.
for
The for loop repeats a group of statements a fixed, predetermined number of
times. A matching
end delineates the statements:
forn=3:32
r(n) = rank(magic(n));
end
r
The semicolon terminating the inner statement suppresses repeated printing,
and the
r after the loop displays the final result.
It is a go o d ide a to indent the loops for readability, especially when they are
nested:
fori=1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end
while
The while loop repeats a group of statements an indefinite number of times
under control of a logical condition. A matching
end delineates the statements.
Here is a complete program, illustrating
while, if, else,andend,thatuses
interval bisection to find a zero of a polynomial:
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > ep s*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
4-5
Commenti su questo manuale