A Quick Introduction To Loops in Matlab: See Pp. 102-105 For A Description of The Fprintf Statement
A Quick Introduction To Loops in Matlab: See Pp. 102-105 For A Description of The Fprintf Statement
page 1/3
for Loops
for loops are often used when a sequence of operations is to be performed a predetermined number of times. For example computing the average of a list of numbers requires adding up a known number of values. Syntax Loop counter incremented by one:
for i = startValue:endValue x = ... y = ... . . . end
i is the loop counter. On the rst pass through the loop, i is set to startValue. On the second pass through the loop i is set to startValue+1. The Matlab statements between the for and the end are evaluated until i>endValue Example 1 Print the square root of the rst n integers
%8.4f\n,i,sqrt(i));
The increment can be any positive or negative number Example 2 Print the square root of the even integers up to n
%8.4f\n,i,sqrt(i));
for Loops
page 2/3
or negative
for i = 5:-1:-5 ... end
The startValue, increment, and endValue parameters do not need to be integers Example 3 Print the sine and cosine of a list of angles
for a=0:pi/6:pi d = a*180/pi; % convert to degrees fprintf(%8.3f %8.1f %9.4f %9.4f\n,a,d,sin(a),cos(a)); end
Pre- and Post-loop Processing Many loops involve manipulating quantities that are dened before the loop begins. Example 4 Compute the sum of the rst n integers
n = s = for s end 10; 0; i=1:n = s + i;
The variable s must exist, and have a meaningful value before the loop begins. Otherwise the expression s + i cannot be evaluated. The expression s = s + i is not a mathematical equation, it is an assignment. Mentally replace the = sign with an assignment arrow like . s=s+i means ss+i The statement s = 0 is called an initialization of s because it gives s its initial value before the loop starts.
for Loops
page 3/3
Loops can involve many repetitions, so printing during each pass through a loop is often impractical and undesirable. In some cases, a message or other clean-up work is done after the loop is nished. Example 5 Compute the average of a list of numbers
n = 500; x = rand(1,n); s = 0; for i=1:n s = s + x(i); end xbar = s/n;
The expression x = rand(1,n) creates a row vector of n pseudo-random numbers. The expression s = s + x(i) adds the ith element of x to the sum. As in Example 4, an initial value of s must be assigned before the loop starts. The average value (xbar) can only be computed after the loop is nished.