Leastsq sudden problem

Dear colleagues,

for years, I have successfully used “leastsq” and, suddenly, it gives wrong results. What had happened?

Heinz

// ------------------------------------------------------------------
// EMG fit (p = [mu, 1/lambda, sigma])
// • Model fitted as Frequency = f(Height)
// ------------------------------------------------------------------
clear; clc; close;

// 1. Load data ----------------------------------------------------
data = csvRead("histogramm_height_RK.csv", ";");
h = data(2:$, 1); // Height (m)
f = data(2:$, 2); // Frequency (counts)

// 2. Normalisation --------------------------------------------------
yy=f/sum(f)/2;

// 3. EMG function --------------------------------------------------
function yhat=pred(p, x)
a = 1 / p(2); // lambda
s = p(3); // sigma
xx = x - p(1); // x - mu
yhat = (a/2) .* exp((a/2) .* ((a*s^2) - 2*xx)) ...
.* erfc((a*s^2 - xx) ./ (s*sqrt(2)));
endfunction

// 4. Initial guess μ, τ=1/λ, σ and nonlinear least-squares fitting
p0=[5.73; 10.76; 75.1]
[fopt,p,gopt] = leastsq( #(p)->(pred(p,h)-yy) , p0);

// 5. Final result --- IS WRONG !
disp(p)

histogramm_height_RK.csv (1.6 KB)

Why do you say that results are wrong ? When increasing the verbosity:

[fopt,p,gopt] = leastsq(iprint=2, #(p)->(pred(p,h)-yy) , p0);
***** enters -qn code- (without bound cstr)
dimension=         3, epsq=  0.2220446049250313E-15, verbosity level: iprint=         2
max number of iterations allowed: iter=       100
max number of calls to costf allowed: nap=       100
------------------------------------------------
 iter num    1, nb calls=   1, f= 0.5649E-03
 iter num    2, nb calls=   6, f= 0.2239E-03
 iter num    3, nb calls=   7, f= 0.1741E-03
 iter num    4, nb calls=   9, f= 0.1630E-03
 iter num    5, nb calls=  10, f= 0.1452E-03
 iter num    6, nb calls=  11, f= 0.1170E-03
 iter num    7, nb calls=  12, f= 0.6976E-04
 iter num    8, nb calls=  13, f= 0.2580E-04
 iter num    9, nb calls=  15, f= 0.1072E-04
 iter num   10, nb calls=  17, f= 0.1065E-04
 iter num   11, nb calls=  18, f= 0.1063E-04
 iter num   12, nb calls=  19, f= 0.1063E-04
 iter num   13, nb calls=  20, f= 0.1063E-04
 iter num   14, nb calls=  21, f= 0.1063E-04
 iter num   15, nb calls=  22, f= 0.1063E-04
 iter num   16, nb calls=  33, f= 0.1063E-04
 iter num   16, nb calls=  44, f= 0.1063E-04
***** leaves -qn code-, gradient norm=  0.3476441030722958E-13
optim: End of optimization.

you can see that the optimum is reached. Plotting the fit vs the data confirms this:
plot(h,yy,h,pred(p,h)) legend("data","fit")

SO SORRY: everything is perfect now (diagram below).
Verbosity level is interesting!
Thanks for quick response.
Heinz

(Attachment Red kite flight altitude probabilities.pdf is missing)