% IAP2007 Introduction to MATLAB: Graphics and Visualization
% Instructor: Violeta Ivanova, violeta@mit.edu

% ANIMATION EXAMPLE: HELIX
% A Helix is a 3D curve, described by coordinates:
% x = a*cos(t); y = a*sin(t); z = b*t

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% A. CREATE ANIMATION

% A1. Create a Figure window, if there is none open.
figure

% A2. Set the attribute DoubleBuffer of the current figure to On
% so that the plot does not flicker during animation.
set(gcf, 'DoubleBuffer', 'on')

% A3. Define the range of t, and the coefficients a and b of the Helix.
t = [0 : 0.02*pi : 6*pi];
a = 2; b = 1;

% A4. Draw the Helix in 3D, redrawing the plot after adding every point.
set(gcf, 'Name', 'Helix Animation')

for i=1:length(t)
    
   plot3(a*cos(t(i)), a*sin(t(i)), b*t(i), 'ro');
   hold on
   % Set the axes to be the same during plotting
   set(gca, 'XLim', [-2 2], 'YLim', [-2 2], 'ZLim', [0 20])
   drawnow
   
   % Save the frame in a matrix M to play later - see part B.
   M(i) = getframe(gcf);
   
end
hold off

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% B. REPLAY ANIMATION 

% B1. See animation in MATLAB 
% Run this file by typing in the Command Window (uncommented)
% << helix

% B2. Play the animation saved in M in MATLAB
% Try the command below (uncommented) in the Command Window to replay the 
% animation in the Figure window once at 30 frames per second.

% movie(gcf, M, 1, 30)

% B3. Save the animation (uncomment below) in an AVI file
% NOTE: THIS MAY TAKE SOME TIME. THE AVI FILE WILL BE 212 MB!

% movie2avi(M, 'helix.avi', 'fps', 30, 'quality', 100);

% B4. Play the saved file helix.avi in a movie player on your computer.
% Note: This will play fine on Windows. AVI is a Windows format.
% On a Mac it may not play in the Quicktime Player.
% On Mac OS X you can use a program like the VLC Media Player. 
% On Athena, you can use the xanim program:
% athena% add graphics
% athena% xanim helix.avi

