Search code examples
matlabcurve-fittingnon-linear-regression

nsqnonlin - Incorrect convergence - Fitted curve does not model my data at all


Below, the red crosses are the data, and the blue line is the fit curve.

Data and fit curve - image

This is the function being fit:

function diff = fit_simp(x,X,Y)

% This function is called by lsqnonlin.
% x is a vector which contains the coefficients of the
% equation.  X and Y are the option data sets that were
% passed to lsqnonlin.

A1 = x(1);
A2 = x(2);
mode1 = x(3);
mode2 = x(4);
sig1 = x(5);
sig2 = x(6);
alpha = x(7);
beta = x(8);
gamma = x(9);
diff = (A1/(sqrt(2*pi)*sig1))*exp(-0.5.*((X-mode1)/sig1).^2) + (A2/(sqrt(2*pi)*sig2))*exp(-0.5.*((X-mode2)/sig2).^2) + alpha + beta*X + gamma*X.*X

My starting values are:

X0=[0.1 0.02 0.6 1.2 1 1 0.1 -0.2 0.011]

The final message from MATLAB:

Optimization completed: The first-order optimality measure, 3.114006e-10,
is less than options.OptimalityTolerance = 1.000000e-06.

Optimization Metric                                       Options
relative first-order optimality =   3.11e-10  OptimalityTolerance =   1e-06 (default)

Is there something I'm missing? It works for simpler functions.


Solution

  • You are not using your Y data. Now, your diff is the evaluation of your model at the points X for the parameters x, but you should return diff - Y. lsqnonlin will minimise the norm of the returned value. That is indeed what you got, a function which is (almost) zero everywhere.