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 (linear, quadratic, or cubic), and x for f(x).
Code with commments
clc; clear all; close all;
x = input('Enter x values: '); %input x vector
y = input('Enter y values: '); %input y vector
n = input('Enter n: '); %input n
xpred = input('Enter x for f(x): '); %input x vector for
prediction
p = polyfit(x,y,n); %least square fitting
disp('Fitted Least square Polynomial: ');
p
disp('Predicted values: ');
for i=1:length(xpred)
fprintf("x: %.2f, prediction: %.2f\n",xpred(i),
polyval(p,xpred(i)));
end
%extra
%plotting graph to visualize fitting
hold on;
scatter(x,y);
plot(x, polyval(p,x))