Exercise 6.6: Find the best-fitting quadratic y = a*x^2 + b*x + c to
the data
x || -2 | -1 | 1 | 2 | 3
---++----+----+----+----+----
y || 2 | 1 | -1 | 0 | 2
We use the polyfit of MATLAB to solve this problem:
>> x = [-2 -1 1 2 3]
x =
-2 -1 1 2 3
>> y = [2 1 -1 0 2]
y =
2 1 -1 0 2
>> c = polyfit(x,y,2)
c =
0.4529 -0.5503 -0.5909
% The vector c contains the a, b and c of the quadratic
% y = a*x^2 + b*x + c in its entries.
% Now we plot the results, first defining the plot range
r = -2:0.1:3;
f = polyval(c,r);
plot(r,f)
hold on
plot(x,y,'r+')
Here is the plot: