I need help figuring out the mistake in my function approximation

4 views (last 30 days)
I am doing function approximation but i'm not getting a smooth function at all. I've tried least squares method and backslash for the same question. Could someone please point out my mistake and help me? Thank you.

Accepted Answer

the cyclist
the cyclist on 26 Oct 2023
Your 5th-degree polynomial is smooth (but not unique, because you only have 4 data points). You just don't plot on a fine enough grid to see it. Here, I plot just your 2nd and 5th-order polynomials, on a finer grid.
x = [0.1 0.3 0.4 0.6 0.9];
y = [0 2.2 1 0.6 3.7];
x0 = 0 : 0.02 : 0.9;
for m = [2 5]
P = polyfit(x,y,m);
yaprox = polyval(P,x);
yaprox0 = polyval(P,x0);
figure
hold on
plot(x,y,'o','MarkerSize',8);
plot(x0,yaprox0,'ro-','MarkerSize',2);
xlabel('x')
ylabel('y')
legend('data','fit')
end
Warning: Polynomial is not unique; degree >= number of data points.

More Answers (1)

John D'Errico
John D'Errico on 26 Oct 2023
Edited: John D'Errico on 26 Oct 2023
Avoid the use of the normal equations as you used, i.e., this crapola that you called the least squares method. Backslash is just as much a least squares method!
% A = [sum(x.^2) sum(x.^3)
% sum(x.^3) sum(x.^4)];
% b = [sum(y.*x);sum(y.*x.^2)];
%
% % solution of the system
% c = inv(A)*b;
Properly solve for the coefficients using backslash.
x = [0.1 0.4 0.9 1.6 1.8]';
y = [0.4 1.0 1.8 4.1 5.5]';
Your model is: f(x) = c1x + c2x^2
A = [x,x.^2];
C12 = A\y;
plot(x,y,'o');
hold on
yfun = @(X) C12(1)*X + C12(2)*X.^2;
fplot(yfun,[min(x),max(x)])
Note my use of fplot there. Your evaluation of the points on the curve
% xx = x(1):0.1:x(end);
was a bad idea. Why? How many points did it generate? LOOK CAREFULLY! Just because 0.1 seems like a small number, IS IT REALLY????? What is x again?
x = [0.1 0.4 0.9 1.6 1.8]';
Alternatively, you might have used linspace to generate that vector. I would suggest your real problem was in just the use of a stride of 0.1 between points to evaluate the curve at.

Categories

Find more on Polynomials 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!