Solutions

1. Write a function called linEst(v1,v2), which takes two vectors as input. These two vectors are the x and y coordinates of our measured data points. Find the most fitting straight line in least square sense, and plot it with the data points. The output of your function is the steepness of the straight line.

function m=linEst(v1,v2)
coeff1=polyfit(v1,v2,1);
m=coeff1(1);

hold on
plot(v1,v2,'r*');
rangeofpoints=linspace(min(v1),max(v1));
plot(rangeofpoints,polyval(coeff1,rangeofpoints))



2. Our data point are the following: the x coordinates are (0.5, 1, 1.5, 2, 2.5, 3, 3.5) the y coordinates are (3.27, 6.1, 9.7, 12.9, 15.1, 19.4, 21.3). Write a function called estMate(n), which takes a positive integer as input. The function calculates the best fitting at most n degree polynomial, and plots it and the data points. The function also saves the plot to an jpg file.

function fel2(n)
datap=[0.5, 1, 1.5, 2, 2.5, 3, 3.5];
fvalues=[3.27, 6.1, 9.7, 12.9, 15.1, 19.4, 21.3];
coeffs=polyfit(datap,fvalues,n);


hold on
plot(datap,fvalues,'r*');
rangeofdp=linspace(0.5,3.5);
plot(rangeofdp,polyval(coeffs,rangeofdp))
saveas(gca,'poitns.jpg')



3. Write a function called rungeCo(n), which takes a positive integer as input. The function calculates the best fitting at most n-1 degree polynomial for the following problem: we take n equidistant points on the interval [-5,5]. These point are the x coordinates of our data points. The y coordinates are 1/(1+x^2). Plot the f(x)=1/(1+x^2) function and the fitted polynomial for n=5 and n=15.

function rungCo(n)

datap=linspace(-5,5,n);
fvalue=1./(datap.^2+1);

k=0:n;
datap2=5*cos((2*k+1)./(2*n+2)*pi);
fvalue2=1./(datap2.^2+1);

coeffs1=polyfit(datap,fvalue,n-1);
coeffs2=polyfit(datap2,fvalue2,n-1);
t=linspace(-5,5,n*100);

plot(t,1./(1+t.^2),'b',t, polyval(coeffs1,t), 'r',t, polyval(coeffs2,t), 'k')
legend('Original function', 'Equidistant','Chebyshev')

4. Write a function called interpolals(x,y,x0) which takes two vectors (x and y coordinates of the data points), and a floating point number x0. The output of your function is the estimated function value in x1 using spline interpolation.

function ki=interpolals(x,y,x0) 

ki=spline(x,y,x0);