Least Squares method code
3 views (last 30 days)
Show older comments
X =input('Enter list of abscissas: ');
Y = input('Enter list of ordinates: ');
F = input('Enter 1 for linear fit, 2 for parabolic: ');
n = length(X);
N = F+1;
A= zeros(N,N);
for i=1:N
for j=1:N
A(i,j) = sum(X.^(i+j-2));
end
end
B= zeros(N,1);
for k=1:N
B(k) = sum((X.^(k-1)).*Y);
end
U=A\B;
% hien thi parabol
disp('Your polynomial is:')
grid on
for k=N:-1:2
fprintf('+(%.(4fx^%d)',U(k),k-1)
end
fprintf('+(%.4f)\n', U(1))
%plotting
P = flip(U);
x = linspace(X(1),X(n),100);
y = polyval(P,x);
plot (x,y,'r')
hold on
plot(x,y,'o')

can someone turn that picture into something like this picture

or like a line when i choose F=1
Answers (1)
William Rose
on 11 Dec 2022
Edited: William Rose
on 11 Dec 2022
@A,
[edit: I adjusted the fprintf() lines to produce better output.]
X = [0.8; 1.4; 2.7; 3.8; 4.8; 4.9];
Y = [0.69; 1.0; 2.02; 2.39; 2.34; 2.83];
%F = input('Enter 1 for linear fit, 2 for parabolic: ');
F=2;
n = length(X);
N = F+1;
A= zeros(N,N);
for i=1:N
for j=1:N
A(i,j) = sum(X.^(i+j-2));
end
end
B= zeros(N,1);
for k=1:N
B(k) = sum((X.^(k-1)).*Y);
end
U=A\B;
% hien thi parabol
disp('Your polynomial is:')
for k=N:-1:2
fprintf('%+.4f x^%d ',U(k),k-1)
end
fprintf(' %+.4f \n', U(1))
%plotting
P = flip(U);
x = linspace(X(1),X(n),100);
y = polyval(P,x);
plot (x,y,'-r',X,Y,'b*')
legend('Fit','Data')
The above code uses F=2, i.e. parabolic fit. Good luck.
0 Comments
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!