Least Squares method code

3 views (last 30 days)
A
A on 10 Dec 2022
Edited: William Rose on 11 Dec 2022
X =input('Enter list of abscissas: ');
Unable to run the 'fevalJSON' function because it calls the 'input' function, which is not supported for this product offering.
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
  2 Comments
A
A on 11 Dec 2022
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]

Sign in to comment.

Answers (1)

William Rose
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:')
Your polynomial is:
for k=N:-1:2
fprintf('%+.4f x^%d ',U(k),k-1)
end
-0.0947 x^2 +1.0215 x^1
fprintf(' %+.4f \n', U(1))
-0.1283
%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.

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by