function [coef, RSquared]=plotfit(x,y,polyorder) % plotfit(,y,polyorder) plots x,y data in the vectors "x" % and "y", fits it to a polynomial of order "polyorder", % plots the data and the fit, and displays the fit % coefficients and the goodness-of-fit measure R-squared % in the upper left corner of the graph. % polyorder=1 for straight line, =2 for quadratic (parabola) etc. % Tom O'Haver, 2008 coef=polyfit(x,y,polyorder); % Plot the data and the polynomial fit xx=linspace(min(x),max(x)); yhat=polyval(coef,xx); plot(x,y,'.r',xx,yhat,'-g') axis([min(x) max(x) min(y) 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(min(x),max(y)-.05.*(max(y)-min(y)),[' Polynomial Order of fit = ' num2str(polyorder)] ); text(min(x),max(y)-.1.*(max(y)-min(y)),[' Fit coefficients = ' num2str(coef)] ); text(min(x),max(y)-.15.*(max(y)-min(y)),[' R-Squared = ' num2str(RSquared)] );