Non linear fit extremely bad : what am I doing wrong ?

9 views (last 30 days)
Hello everybody,
I've spent my evening trying to understand why the nonlinear fit was so bad with my data and I couldn't find why.
I tried many different options, like the 'fit' function, 'fminsearsh', the fitting curve tool, etc...
For some reasons, the fit is OK only if my starting points are close from the real coeff at 0.1% ...
What am I doing wrong ? 1.1 isn't THAT far from 1. (same problem without the constant 'a')
Thank you for your help,
close all
clear all
rng('default')
t = 0:0.02:10; x = t.*sin(2*pi*1*t) + 0.1*randn(1, length(t)); % x*sin(x) with noise
x = x'; t = t';
% fitting part
x0 = [0 1.1];
fitfun = fittype( @(a,b,x) a+x.*sin(2*pi*b*x) );
[fitted_curve,gof] = fit(t,x,fitfun,'StartPoint',x0)
fitted_curve =
General model: fitted_curve(x) = a+x.*sin(2*pi*b*x) Coefficients (with 95% confidence bounds): a = -0.1064 (-0.5048, 0.292) b = 1.117 (1.115, 1.119)
gof = struct with fields:
sse: 1.0263e+04 rsquare: -0.2337 dfe: 499 adjrsquare: -0.2362 rmse: 4.5352

Accepted Answer

Matt J
Matt J on 14 Mar 2024
Edited: Matt J on 15 Mar 2024
There are ways to derive an accurate x0 more systematically, e.g.,
rng('default')
t = 0:0.02:10; x = t.*sin(2*pi*1*t) + 0.1*randn(1, length(t)); % x*sin(x) with noise
x = x'; t = t';
%Coarse fit
a0=mean(x);
I=t>=1;
z=(x(I)-a0)./t(I); %Ideally, z would be purely sinusoidal
cfit=fit(t(I),z,'fourier1');
% Fine fit
x0 = [a0 cfit.w/2/pi];
fitfun = fittype( @(a,b,x) a+x.*sin(2*pi*b*x) );
[cfit,gof] = fit(t,x,fitfun,'StartPoint',x0),
cfit =
General model: cfit(x) = a+x.*sin(2*pi*b*x) Coefficients (with 95% confidence bounds): a = -0.002197 (-0.01101, 0.006614) b = 1 (0.9999, 1)
gof = struct with fields:
sse: 5.0280 rsquare: 0.9994 dfe: 499 adjrsquare: 0.9994 rmse: 0.1004
plot(cfit,t,x)
  1 Comment
Nassim Mhammedi
Nassim Mhammedi on 15 Mar 2024
Indeed I should've known that the search for starting points is part of the work.
Thank you for your answer and the elegant code!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!