Least Squares method code

5 次查看(过去 30 天)
A
A 2022-12-10
编辑: William Rose 2022-12-11
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 个评论
Image Analyst
Image Analyst 2022-12-10
What values did you type in?
A
A 2022-12-11
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]

请先登录,再进行评论。

回答(1 个)

William Rose
William Rose 2022-12-11
编辑:William Rose 2022-12-11
@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.

类别

Help CenterFile Exchange 中查找有关 Particle & Nuclear Physics 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by