%%

%Approximation/Interpolation of functions

%points given by the table
x = 1:9;
y = [1:3,5:-1:4,1:4];
%division for the splines calculation
division = 1:0.1:9;

%Interpolation by polynomial function (for 9 points we have polynomial function of 8th order)
P = polyfit(x,y,length(x)-1)
%If we use polynomial function of order lower than 8 Matlab uses least
%squares method to approximate the function, i.e., it is not interpolation

%verification of the interpolation, i.e., function includes all the y
%points
yap = polyval(P,x)

%Plot of points and the interpolating function
plot(x,y,'ro',x,yap)

%Using lower order polynomial function
P_low = polyfit(x,y,2)

yap_low = polyval(P_low,x)

figure %figure new window
plot(x,y,'ro',x,yap_low) %function is not fitting the points given by the table

%Interpolation using spline functions
yspl_near = interp1(x,y,division, 'nearest') %partially constant function
yspl_linear = interp1(x,y,division, 'linear') %partially linear function
yspl_cubic = interp1(x,y,division, 'cubic') %partially cubic function

figure
plot(x,y,'ro') %original points from the table

hold on %all into one plot
%draw different splines - constant, linear, cubic
plot(division,yspl_near) 
plot(division,yspl_linear,'k')
plot(division,yspl_cubic,'m')

hold off
