% MATLAB SAMPLE: list-serve email and posted on 293 home page
%      by Andy Ruina on 9/20/96
%
% Here is a script file that contains some MATLAB samples:
%      Loops,            (FOR and WHILE)
%      overlayed plots   (PLOT and HOLD), and
%      picking out the last element of a vector   (LENGTH).
%
% This is not a solution to HW4.
% It contains stuff which might be useful for HW4.
% To get more documentation on the commands used here
% use MATLAB help or, say, Pratap's book.
%
% This file runs as written.  Try it. Understand it. Change it.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A SIMPLE  'FOR' LOOP.  See, eg., Pratap pg 92.
x=0;
for i=0:.5:5
    x=x+i;  % the usual weird use of '=' in computer programs
end
x           % reports the sum 0 + .5 + 1 + 1.5 + ... + 5

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SAVING PARTIAL RESULTS
z=0;  ztemp=0;
for i=0:.5:5
    ztemp = ztemp +i;
	z= [z;ztemp];      %adds a new  element to the column z
                       %For online help type  >help punct
                       %See, eg, Pratap pgs 155 &/or  41-47
end

z           % reports the partial sums in a column 'vector':
            %   0 ,  0 + 0, 0 + 0 + .5,  0 + 0 + .5 + 1, ...  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A SIMPLE WHILE LOOP (same result as the for loop above. See Pratap pg 93)
y=0; ytemp=0; i=0;
while i <= 5,
    ytemp = ytemp +i;
	y= [y;ytemp];      %adds a new row (element) to the column y
	i=i+.5;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PICK OFF THE LAST ELEMENT OF A 'VECTOR'  (Pratap, pg 10)
zlast = z(length(z))

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OVERLAY PLOTS                see, eg., Pratap pgs 105-108
% OVERLAY PLOTS: method 1
plot(z,y, z, sin(z))      % The plot is accurate. 
                          % Why doesn't it look like a sine wave?
 
% OVERLAY PLOTS: method 2 (same result as for method 1)
plot(z,y);  
hold on       % saves the plot for future overwriting. 
plot(z,sin(z)); 
hold off      % allows you to make a fresh new plot
