کد:
% Start fresh
clear all
% Program header
disp('Demonstrate how to fit data with a polynomial with "polyfit".')
% Create independent variable (ranging from -10 to 10 with an increment of 0.1.
% Row vector works as well.
x = [-10 : 0.1 : 10]';
% Create data to be fitted
y = 1 ./ (x.*x+1);
% Find the polynomial coefficients by calling the "polyfit" function
a = polyfit(x, y, 8);
% Print the coefficients (The coefficients are reversed)
disp('The coefficients are (from the highest order down): ')
for i=1 : size(a,2)
fprintf('a(%2i) = %14.6e\n', i, a(i))
end
% Generate the fitted polynomial function with "polyval"
yfit = polyval(a, x);
% Plot and compare results
plot(x, y, 'o', x, yfit, '-')