clear all; close all

load peak.dat
xd=peak(:,1);
yd=peak(:,2);
plot(xd,yd,'O:')

% COSINE fit: a*cos(b*x)
% look for a reasonable initial guess for a,b
xp=linspace(-3,3,100);
a=2; b=0.7;
yp=a*cos(b*xp);
figure(1)
plot(xd,yd,'bO:',xp,yp,'r')
% set up fminsearch to minimize 2-norm of the residual vector
par0=[a b]; % put initial guess for a,b in an array
cos_coeff=fminsearch('cos_res',par0,[],xd,yd);
% assign results of fminsearch to the parameters
a=cos_coeff(1)
b=cos_coeff(2)
% plot the fitted curve
yp=a*cos(b*xp);
figure(2)
plot(xd,yd,'bO:',xp,yp,'r')
% evaluate the root-mean-square error of the fit
n=length(xd);
yf=a*cos(b*xd);
E2cos=sqrt( sum((yd-yf).^2)/n )

clear a b par0 yp yf

% GAUSSIAN fit: a*exp(-b*x^2)
% look for a reasonable initial guess for a,b
xp=linspace(-3,3,100);
a=2; b=1;
yp=a*exp(-b*xp.^2);
figure(3)
plot(xd,yd,'bO:',xp,yp,'r')
% set up fminsearch to minimize 2-norm of the residual vector
par0=[a b]; % put initial guess for a,b in an array
gauss_coeff=fminsearch('gauss_res',par0,[],xd,yd);
% assign results of fminsearch to the parameters
a=gauss_coeff(1)
b=gauss_coeff(2)
% plot the fitted curve
yp=a*exp(-b*xp.^2);
figure(4)
plot(xd,yd,'bO:',xp,yp,'r')
% evaluate the root-mean-square error of the fit
n=length(xd);
yf=a*exp(-b*xd.^2);
E2gauss=sqrt( sum((yd-yf).^2)/n )
