% 4-18-2008 % MATLAB data fitting examples clear all; close all; % Load the data load linefit.dat; x = linefit(:,1); y = linefit(:,2); % These are the points we would like to interpolate to xp = 0:0.1:7; % Polynomial fits P1 = polyfit(x,y,1); yp1 = polyval(P1,xp); P2 = polyfit(x,y,2); yp2 = polyval(P2,xp); P3 = polyfit(x,y,3); yp3 = polyval(P3,xp); % E_2 error E_2_1 = sqrt( 1/length(x) * sum( abs(polyval(P1,x) - y).^2 ) ) E_2_2 = sqrt( 1/length(x) * sum( abs(polyval(P2,x) - y).^2 ) ) E_2_3 = sqrt( 1/length(x) * sum( abs(polyval(P3,x) - y).^2 ) ) % Piecewise defined fitting functions yp4 = interp1(x,y,xp); % Linear functions yp5 = spline(x,y,xp); % Cubic functions (splines) figure(1) plot(x,y,'o:') hold on plot(xp,yp1,'r') plot(xp,yp2,'k') plot(xp,yp3,'g') plot(xp,yp4,'c') plot(xp,yp5,'b') % Load gaussian data load gaussfit.dat; x=gaussfit(:,1); y=gaussfit(:,2); % Interpolated points xp=-3:0.01:2.5; % Search for the minimum error with an initial guess of [1 1] C=fminsearch('gafit',[1 1]); figure(2) plot(x,y,'o:'); hold on plot(xp,C(1)*exp(-C(2).*xp.^2),'k')