MATLAB

5. Control Loops for, while if

for Loops

A for loop allows a group of commands to be repeated a fixed predetermined number of times. It is typically of the form

for variable=start:step:finish

commands .......

................

end

Note that variable is not an array variable, but a scalar variable that runs through all the numbers in the array start:step:finish one at a time.

Example 1: Calculate the following using both (i) arrays and (ii) for loops:

1 + 1.1 + 1.2 + . . . + 3 and 1 × 1.1 × 1.2 × . . . × 3

(i) clear all                                                              (ii) clear all

     x=[1:0.1:3];                                                           s=1;

     total=sum(x)                                                          p=1;

     product=prod(x)                                                    for t=1.1:0.1:3

                                                                                          s=s+t ; p=p*t ;

                                                                                   end

                                                                                   total=s

                                                                                   product=p

Example 2: Write a simple M-file to produce the following graphic. Use the fact that x = cos(t), y = sin(t), 0 ≤ t ≤ 2π, is the (assumed known!) parametric representation of the unit circle centred at the origin.

circle

 

 

clear all

t=linspace(0,2*pi,181);

% use 181 points to plot circle

x=cos(t); y=sin(t);

plot(x,y)

axis equal, axis off

hold on

for i=1:20:161

% each line needs 2 x-values and 2 y-values only

plot([0 x(i)],[0 y(i)])

end

hold off

 

Example 3: Suppose you wish to construct a table of values which converts degrees C into degrees F using the standard formula F = 1.8C + 32 for C = 25, 26, 27, . . . , 40.

clear all

fprintf(’ deg C \t deg F \n’) % \t leaves space \n goes to new line

for C=25:40

    F=1.8*C+32; % do not print yet, use fprintf instead to line up

    fprintf(’%4.0f \t %5.1f \n’,[C F])

end