function a_coeff = polynomial_fit(x, y, n) %POLYNOMIAL_FIT Fit polynomial to data. % POLYNOMIALFIT(X,Y,N) finds the coefficients of a polynomial P(X) of % degree N that fits the data, P(X(I))~=Y(I), in a least-squares sense. % % Inputs: % X: a vector of data points x (the independent variable) % Y: a vector of data points y (the dependent variable) % N: the order of the polynomial % % Outputs: % A_COEFF: a vector of coefficients [a_n a_n-1 ... a_1 a_0] representing % the n-th order polynomial (a_i is the coefficient of x^i) % % Assumptions: % - if the degree of the polynomial is large and the data is not well % centered around the origin, then the algorithm may fail due to a % near-singular set of equations. In this case, one should use the % polyfit function (see documentation) % - the variables x and y should have the same size. % - the degree of the polynomial must be >0 %% ME 2016 %% %% AUTHOR: Chris Paredis %% % make sure x and y are both column vectors x=x(:); y=y(:); % create the matrix, z, such that the set of equations: % a_n*(x_i^n) + ... + a_1*x_i + a_0 = y_i % can be represented as z*a=y z = ones(length(x),n+1); for i = 1:n z(:,i) = x.^(n+1-i); end % solve for the coefficients by solving the set of equations in a % least-squares sense a_coeff = (z\y)';