clear all; close all

load velocity.dat
td=velocity(:,1);
yd=velocity(:,2);
plot(td,yd,'O:')

% fit with a*sin(b*(t-c)) + d*t + e
% look for a reasonable initial guess for a,b,c,d,e
tp=linspace(0,30,100);
a=3;
b=2*pi/6;
c=5;
d=2/3;
e=30;
yp=a*sin(b*(tp-c)) + d*tp + e;
figure(1)
plot(td,yd,'bO:',tp,yp,'r')
% set up fminsearch to minimize 2-norm of the residual vector
par0=[a b c d e];
coeff=fminsearch('osc_res',par0,[],td,yd);
% assign results of fminsearch to the parameters
a=coeff(1)
b=coeff(2)
c=coeff(3)
d=coeff(4)
e=coeff(5)
% plot the fitted curve
yp=a*sin(b*(tp-c)) + d*tp + e;
figure(2)
plot(td,yd,'bO:',tp,yp,'r')
% evaluate the root-mean-square error of the fit
n=length(td);
yf=a*sin(b*(td-c)) + d*td + e;
E2cos=sqrt( sum((yd-yf).^2)/n )

