% Example 1) polynom fit to data


% Create data
X = 0:10;
Y = 0.05 - 3.2 * X.^2  + 2 * X.^3;

plot(X,Y,'ro')

disp('Press any key to continue')
pause

% Make third degree polynom fit:  Y = P(4) + P(3)*X + P(2)*X.^2 + P(1)*X.^3

Degree = 3;

Coeffs = polyfit( X,Y, Degree );      % Matlab intrinsic function
% -->  Coeffs =  2.0000   -3.2000   -0.0000    0.0500

fprintf('The coefficients from the fit are are\n')
fprintf('P(4) = %4.3f\n', Coeffs(4) )
fprintf('P(3) = %4.3f\n', Coeffs(3) )
fprintf('P(2) = %4.3f\n', Coeffs(2) )
fprintf('P(1) = %4.3f\n', Coeffs(1) )

% Dra a line with denser grid

XX = 0:0.1:10;
YY = Coeffs(4) + Coeffs(3)*XX + Coeffs(2)*XX.^2  + Coeffs(1)*XX.^3;

plot(X,Y,'ro', XX,YY,'b-')
xlabel('X values')
ylabel('Y values')
legend('Points','Fit')



disp('Press any key to continue with Example 2) ')
pause


% Example 2) Point that rotates around a circle

R   = 1.0;           % Radius of the circle

dt  = 0.1;           % Delta time step

EndT = 10;           % End time

Speed = 2.0;         % Speed (m/s) around the circle

TimeVec = 0 : dt : EndT;  % [ 0 0.1 0.2 ...  10]

Nloop   = length( TimeVec );   % Number of time steps

DistAroundCircle = 0;
Time             = 0;          % Initial time (s)

TimeToPause      = 0.05;


for I = 1:Nloop
    Time             = Time + dt;
    DistAroundCircle = DistAroundCircle + dt*Speed;
    
    Angle = DistAroundCircle / R;   % (rad) Definition of angle
    X     = R * cos(Angle);
    Y     = R * sin(Angle);
    plot( X,Y,'r*' )                % Red star
    axis equal
    axis( [ -R*1.1 R*1.1 -R*1.1 R*1.1] )

    title( [ num2str( Time, '%4.2f') ' s' ] )
    drawnow
    pause( TimeToPause )
    
end












