%% Week 10
% Matlab codes for week 10

%% Problem 1

x=[-1,0,1];
y=[6,3,2];
z=polyfit(x,y,2)
xx=linspace(min(x),max(x),500);
yy=polyval(z,xx);
plot(x,y,'ro',xx,yy,'b-')

%% Problem 2

f=@(x)log(x+1);
x0=0.45;
x=[0,0.6,0.9];
xx=linspace(0,0.9,100);
z=polyfit(x,f(x),2);
yy=polyval(z,xx);
plot(x,f(x),'or',xx,yy,'b-',xx,f(xx),'-k')
legend('nodes','interpolation polynomial','f(x)')
error_at_x0=(f(x0)-polyval(z,x0))

%% Problem 3

f=@(x)sin(x);
x0=0.3; % a given point where we calculate the interpolation error
n=4 % number of the sub-intervals
x=linspace(0,pi,n+1);
xx=linspace(0,pi,100);
yy=interp1(x,f(x),xx,'linear');
plot(x,f(x),'or',xx,yy,'b-',xx,f(xx),'-k')
legend('given points','interpolation polynomial','f(x)')
hiba_x0ban=f(x0)-interp1(x,f(x),x0,'linear')

%% Problem 4

np1=12; 
x0=0.3; % an arbitrary point where the error is checked
f=@(x)1./(1+x.^2);
x=cos(pi/2/np1+[0:np1-1]*pi/np1);
y=f(x);
z=polyfit(x,y,np1-1);
xx=linspace(-1,1,200);
yy=polyval(z,xx);
error_at_x0=abs(f(x0)-polyval(z,x0))

plot(x,y,'ro',xx,yy,'b-',xx,f(xx),'k-')
legend('given points','interpolation polynomial','f(x)')
pause

fs=sym(f)
fders=diff(fs,np1)
fder=matlabFunction(fders)
xx=linspace(-1,1,500);
plot(xx,fder(xx))

%% Problem 5

x=[1,3]; y=[2,1];
s=spline(x,[1,y,2]) % the first and the last elements in the second vector are the derivatives at the endpoints
s.coefs % the coefficients of the polynomial in (x-1) - local coordinates

xx=linspace(1,3,100);
plot(xx,ppval(s,xx),'b-',x,y,'ro')
axis equal

%% Problem 6

x=[1,2,3]; y=[2,1,1];
d=(1/3*[2,1,0;1,4,1;0,1,2])\[-1;-1;0]
s=spline(x,[d(1),y,d(end)]) % 
s.coefs 

xx=linspace(1,3,100);
plot(xx,ppval(s,xx),'b-',x,y,'ro')
axis equal
