format compact
format long
clear
figure( 1 )
clf
hold on

p_real = [1 5 -35 25];

disp( 'Green line - exact function.' )
disp( 'Red circles - inexact measured data.' )
disp( 'Exact polynom coefficients:' );
p_real

x = -10:1:7;

y = x.^3 + 5 * (x - 2).^2 -15 * x + 5;
ierr = 0.2 * max( y );

y = y + ierr * rand( size( y ) ) - 0.5 * ierr;

plot( x, y, 'ro' );

y2 = polyval( p_real, x, 3 );
plot( x, y2, 'g' )

disp( 'Polyfit with degree 3 - press a key' );
pause

n = 3;
[p, s] = polyfit( x, y, n );
[y1, delta] = polyval( p, x, s);

errorbar( x, y1, delta, 'b' );
hold on

disp( 'Polynom coefficients:' );
p

disp( 'Polyfit with degree 15 - press a key' );
pause

n = 15;
[p, s] = polyfit( x, y, n );
[y1, delta] = polyval( p, x, s);

plot ( x, y1,  'k' );
hold on

disp( 'Polynom coefficients:' );
p

disp( 'It is worse than the previous case!' );

disp( 'Interpolation (slow) - press a key' );
pause

tic
x_int = -10:0.2:7;
y_int = lagrange( x_int, x, y );
plot( x_int, y_int, 'm' )
toc

disp( 'And this is the worst...' )