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에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by