% Simple curve fitting example using polyfit and polyval, and corrcoef % Change the numbers in lines 6-10 to modify the data. Change the % polynomial order in line 16 (quadratic=2, cubic=3, etc) % Define the model parameters x=[0:30]; % Defines the independent variable (x-axis) intercept=1; slope=1; QuadraticTerm=0; noise=2; % Create the model data and add random noise y=intercept+slope.*x+QuadraticTerm.*x.^2+noise.*randn(size(x)); % Fit a polynomial to the data polyorder=1; coef=polyfit(x,y,polyorder); % Plot the data and the polynomial fit xx=linspace(0,max(x)); yhat=polyval(coef,xx); plot(x,y,'.r',xx,yhat,'-g') axis([0 max(x) 0 max(y)]); xlabel('x');ylabel('y') % Compute the correlation coefficient and R-Squared cc=corrcoef(polyval(coef,x),y); RSquared=cc(2).^2; % Label the graph with the fit information text(1,.95.*max(y),[' Polynomial Order of fit = ' num2str(polyorder)] ); text(1,.9.*max(y),[' Fit coefficients = ' num2str(coef)] ); text(1,.85.*max(y),[' R-Squared = ' num2str(RSquared)] );