for’ Loops

 

Using ‘for’ Loops

 

·           First, close all your windows, clear variables, and clear the command window:

 

close all; clear all; clc;

 

·           Here is a loop over k, printing each k as the loop makes a pass:

 

for k=-2:.5:3  % start at –2, step by .5, stop when k > 3

 

              % Put all your statements, that use k in some way, here

              % between the for and the end statement

% Let’s simply print k each time through the “loop”

k

 

end

 

·           Here is a flowchart for the program above.

 

·           Here is a loop using the command fprintf( ):

 

for k=-10:.2:3

fprintf('When you square %.1f you get %.1f \n',k,k^2);

end

 

Note: %.1f à print a floating point decimal with one decimal place.

\n à new line character (don’t forget unless you want your next print out will be on the same line).

 

 

Embedded Loops

 

·           You can use for-loops inside of for-loops (embedded loops).   Here we evaluate the surface z=x^2+y^2

 

 

x=[0:.1:3];

         y=[1:.5:5];

 

for i=1:length(x)

 

for j=1:length(y)

 

z(j,i)=x(i)^2+y(j)^2;

 

end

 

end

 

mesh(x,y,z)

xlabel('x')

ylabel('y')

zlabel('z')

title('z=x^2+y^2')

 

 

 

 

Animations

 

·           We can make an animation of a polynomial with the variable a changing as follows:

 

x=linspace(-5,5,1000);

 

for a=-10:.1:10 

y=a*x.^2;

figure(1)

plot(x,y)

axis([-5,5,-10,40]);             

grid

drawnow                                    

end

 

 

·           You can add a “getframe” command to make a MATLAB movie array