% Introduction to MATLAB 
% Programming
% CC Violeta Ivanova, MIT Information Services and Technology

% Example One - A Cubic Fit to Data Points
% This program computes the cubic fit to five points
% and creates an animated plot.

% Create vectors X, Y with coordinates of data points
X = [2 3 5 6 8]'
Y = [75 86 82 70 40]'

% Compute cubic fit using the built-in function polyfit
C = polyfit(X, Y, 3)

% Compute the interval x for the cubic fit computation
x = [0 : 0.1 : 10];

% Evaluate the cubic fit over x using the built-in function polyval
y = polyval(C, x);

% Create a plot with the input points X, Y
figure
set(gcf, 'Name', 'Cubic Fit Animation');

plot (X, Y, 'ro', 'MarkerFaceColor', 'r');
hold on

% Add the cubic fit to the figure (animation)

N = length(x);

for i = 1 : N
   
   % Plot every point x(i), y(i) 
   p1 = plot(x(i), y(i), 'bo', 'MarkerSize', 4);
   hold on
   
   % Set the axes to be the same during plotting
   set(gca, 'XLim', [0 10], 'YLim', [0 100]);
   
   % Redraw after adding every point
   drawnow
   
   % Optional - Uncomment to save the frame in a matrix M to play later.
   % M(i) = getframe(gcf);
   
end
hold off

% Optional - Uncomment to export the frames into an AVI file
% movie2avi(M, 'cubic.avi', 'fps', 30, 'quality', 100);