I have some simple time vs position data that I am trying to fit using any of matlab's optimization functions. I've given an example of the data (shown in blue) and the sinusoidal fit I am getting when using lsqnonlin (shown in red). 1
I know my fits are somewhat sensitive to the initial conditions, but I also know the amplitude of my data are very close to ~1 and the frequency is very close to 6 Hz. Despite using initial guesses close to the actual values, the curve-fitting only works on approximately 1 out of every 3 curves I try to fit. Why could something like this be happening?
For reference, here is the function I have written which is getting optimized (Note: my data already has mean=0 so I don't need an offset term):
function [err,pred] = sine_fit2(k,x,y)
pred = k(1)*sin(2*pi*x./k(2))+k(3)*cos(2*pi*x./k(2));
err=(y-pred);
end
I've tried a few different optimization functions in matlab, including: lsqnonlin, lsqcurvefit, fminsearch, fminunc
I've also played around with the initial conditions (IC) and found that, for example, curve A might be fit well with IC#1, but not with IC#2, whereas curve B is fit poorly when using IC#1, but fit well when using IC#2, etc.
Seeing as the data is pretty clean, I'm really surprised the optimization routines are not able to find the correct parameters. Maybe I am doing something really silly! Any help/explanations are much appreciated
EDIT (11/6/2017 @7:30AM) Here is how I am calling my optimization:
% initial guesses
k0 = [1,1/6,1];
% y = data I'm trying to fit
% t = independent variable (time)
[k_opt] = lsqnonlin(@(k)sine_fit2(k,t,y),k0,[],[],lsq_options);
[error,prediction] = sine_fit2(k_opt,t,y);
Also, here is an example of the data I'm trying to fit (note that I multiplied y by 100 to get more significant figures to display):
t y*100
0 0.1225
0.0435 -0.0698
0.0870 -0.0550
0.1304 0.0410
0.1739 -0.0908
0.2174 -0.1034
0.2609 0.0671
0.3043 0.0044
0.3478 -0.0630
0.3913 0.1045
0.4348 0.1177
0.4783 -0.0324
0.5217 0.0332
0.5652 0.0886
0.6087 -0.0767
0.6522 -0.0867
0.6957 0.0586
0.7391 -0.0534
0.7826 -0.1024
0.8261 0.0948
0.8696 0.0441
0.9130 -0.1001
0.9565 0.0114
1.0000 0.0457