% MATLAB Built-In Function polyfit and polyval % % POLYFIT fit polynomial to data. % P = POLYFIT(X, Y, N) finds the coefficients of a polynomial % P(X) of degree N that fits the data Y best in a least-squares % sense. P is a row vector of length N+1 containing the polynomial % coefficents in descending powers, P(1)*X^N + P(2)*X^(N-1) + ... + % P(N)*X + P(N+1). % % Example: Curve Fit: polyfit Function % Using the polyfit function, find and plot the third degree % polynomial that best fits the data x and y arrays % allocate array x from 0 to 1.2 with step 0.3 x = 0:0.3:1.2; % specify y array y = [3.6 4.8 5.9 7.6 10.9]; % call the polyfit function for a third-degree polynomial % that best fits the data in the x and y array P = polyfit(x, y, 3); % display the coefficients disp(P); % generate 100 points for plotting purposes xi = linspace(0, 1.2); % evaluate the polynomial at these points yi = polyval(P, xi); % draw the cubic polynomial fit plot(xi, yi) hold on % draw the x and y array points plot(x, y, 'o')