In: Computer Science
Write a MATLAB script file that will give the value of f(x) using method of least squares and asks the user to enter values of x, y, n (curve fit), and x for f(x).
x=input('Enter row vector containing x values: ');
y=input('Enter row vector containing y values: ');
N=input('Enter n(maximum power): ');
xx=input('Enter the value to evaluate the fitted curve at:
');
if N>length(x)
disp('n must be less than or equal to number of available
points!!!')
else
%creating vander monde matrix
n=N:-1:0;
A=(x').^(n);
b=y';
p=A\b;
%p contains the coefficients of fitted curve
%from highest power to the constant term
disp('Coefficients: ');
disp(p)
yy = polyval(p,xx);
fprintf('Value at %g: %g\n',xx,yy);
%uncomment below lines to plot fit
%plot(x,y,'*');
%hold on
%xx=linspace(min(x),max(x),200);
%plot(xx,polyval(p,xx))
%grid on
%legend('data','Fit')
end