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 Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by