• No results found

A loop is a structure that allows a group of commands to be repeated.

for Loop

A for loop repeats a group of commands a fixed, predetermined number of times. A for loop has the following structure:

for variable=expression commands

end

The commands between the for and end statements are executed once for every column in the expression, beginning with the first column and stepping through to the last column. At each step, known as an iteration, the appropriate column of the expression is assigned to the variable. Thus, on step n, column n of the expression is assigned to the variable, which then can be operated on by one of the commands in the loop.

Rules for writing and using a for loop include:

1. If the expression results in an empty matrix, the loop will not be executed. Control will pass directly to the statement following the end statement.

2. If the result of the expression is a scalar, the loop will be executed once, with the variable equal to the value of the scalar.

3. If the result of the expression is a vector, then each time through the loop, the variable will contain the next value in the vector.

4. A for loop cannot be terminated by reassigning the loop variable within the loop.

5. Upon completion of a for loop, the variable contains the last value used.

6. The colon operator can be used to define the expression using the following format for index = initial:increment:limit

Example 8.5 Use of a for statement in a function

Consider writing a user-defined function that searches a matrix input argument for the element with the largest value and returns the indices of that element.

function [r,c] = indmax(x)

% INDMAX returns the row and column indices of

% the maximum-valued element in x [m n] = size(x);

Avoiding Loops

In general, loops should be avoided inMatlab, as they can significantly increase the execution time of a program. Matlab has the capability to increase the size of vectors and matrices dynamically, as can be required by a for loop. For example, a vector can be of length N at the N th iteration of a loop, and at iteration N + 1, Matlab can increase the length of the vector from N to N + 1.

However, this dynamic storage allocation is not accomplished efficiently in terms of computation time.

For example, consider the following script for generating a sine wave:

% sinusoid of length 5000 for t=1:5000

y(t) = sin(2*pi*t/10);

end

This results in a scalar t, with final value 5000, and a vector y, a sine wave with 10 samples per cycle, with 5000 elements. Each time the command inside the for loop is executed, the size of the variable y must be increased by one. The execution time on a certain PC is 7.91 seconds.

Then consider a second script:

% sinusoid of length 10000 for t=1:10000

y(t) = sin(2*pi*t/10);

end

Clearing theMatlab workspace and running this script to produce vector y having 10000 elements requires an execution time on the same PC of 28.56 seconds, nearly four times the execution time of the first script. Forcing Matlab to allocate memory for y each time through the loop takes time, causing the execution time to grow geometrically with the vector length.

To maximize speed, arrays should be preallocated before a for loop is executed. To eliminate the need to increase the length of y each time through the loop, the script could be rewritten as:

% sinusoid of length 10000 with vector preallocation y = zeros(1,10000);

for t=1:10000

y = sin(2*pi*t/10);

end

In this case, y was arbitrarily defined to be a vector of length 10000, with values recomputed in the loop. The computation time in this case was 2.03 seconds.

Execution time can be decreased even further by “vectorizing” the algorithm, applying an operation to an entire vector instead of a single element at a time. Applying this approach to our example of sinusoid generation:

% better method of sinusoid generation t = 1:10000;

y = sin(2*pi*t/10);

This script produces the vector t with 10,000 elements and then the vector y with 10,000 elements, which is the as same y from the second script above. However, again using the same PC, this script executes in 0.06 second, as opposed to 16.04 seconds for the second for loop script, or 1.92 seconds with a for loop and vector preallocation.

while Loop

A while loop repeats a group of commands as long as a specified condition is true. A while loop has the following structure:

while expression commands end

If all elements in expression are true, the commands between the while and end statements are executed. The expression is reevaluated and if all elements are still true, the commands are executed again. If any element in the expression is false, control skips to the statement following the end statement. The variables modified within the loop should include the variables in the expression, or the value of the expression will never change. If the expression is always true (or is a value that is nonzero), the loop becomes an infinite loop.

Example 8.6 Computing the special value eps

Consider the following example of one way to compute the specialMatlab value eps, which is the smallest number that can be added to 1 such that the result is greater than 1 using finite precision:

num = 0;

EPS = 1;

while (1+EPS)>1 EPS=EPS/2;

num = num + 1;

end

num = num - 1 EPS = 2*EPS

Uppercase EPS was used so that theMatlab value eps was not overwritten. EPS starts at 1 and is continually divided in two, as long as (1+EPS)>1 is True (nonzero). EPS eventually gets so small that adding EPS to 1 is no longer greater than 1. The loop then terminates, and EPS is multiplied by 2 because the last division by 2 made it too small by a factor of two. The results:

num =

52 EPS =

2.2204e-016

While Loops and Break

The while loop allows the execution of a set of commands an indefinite number of times. The break command is used to terminate the execution of the loop.

Example 8.7 Use of a while loop to evaluate quadratic polynomials

Consider writing a script to ask the user to input the scalar values for a, b, c, and x and then returns the value of ax2+ bx + c. The program repeats this process until the user enters zero values for all four variables.

% Script to compute ax^2 +bx + c disp(’Quadratic ax^2+bx+c evaluated’) disp(’for user input a, b, c, and x’) a=1; b=1; c=1; x=0;

while a~=0 | b~=0 | c~=0 | x~=0

disp(’Enter a=b=c=x=0 to terminate’) a = input(’Enter value of a: ’);

b = input(’Enter value of b: ’);

c = input(’Enter value of c: ’);

x = input(’Enter value of x: ’);

if a==0 & b==0 & c==0 & x==0 break

end

quadratic = a*x^2 + b*x + c;

disp(’Quadratic result:’) disp(quadratic)

end

Note that this script will display multiple quadratic expression values if arrays are entered for a, b, c, or x. Consider modifying the script to check each input and breaking if any input is not a scalar.