Why is the fit() function producing a horizontal line above my data?
12 views (last 30 days)
Show older comments
Luke Fournier
on 3 Dec 2022
Commented: Walter Roberson
on 4 Dec 2022
I am using the MATLAB fit() function (single exponential) to fit the decay of miniature excitaotry post synaptic current (mEPSC) events. It works really nicely for some events, but for others the fitted curve is simply a flat line above my data (see represemtative image for an example of each). I cannot empirically determine any differences between the events where the fit looks good compared to those where the fit produces the horizontal line. Any ideas?
13 Comments
Accepted Answer
Walter Roberson
on 4 Dec 2022
Activate the "center and scale" option -- but remember that the coefficients you are shown as a result refer to the centered/scaled coordinate system.
3 Comments
Walter Roberson
on 4 Dec 2022
Using @Torsten's flow template from https://www.mathworks.com/matlabcentral/answers/424895-how-can-i-make-logaritmic-fitting-like-polyfit-function#comment_624760 :
format long g
filename = 'for_walter.xlsx';
T = readmatrix(filename);
fx = T(:,4);
fy = T(:,5);
%data contains lots of nan
mask = ~isfinite(fx) | ~isfinite(fy);
fx(mask) = [];
fy(mask) = [];
p = polyfit(fx,log(fy),1)
b = p(1);
a = p(2);
syms x
yfit = exp(sym(a)) * exp(b*x);
for_display = vpa((yfit),16)
Notice the coefficients on the order of 6e+366 -- coefficients that are beyond the range representable by double precision. So when you work in double precision, you cannot get a useful fit.
Let us try a different approach:
syms areal aimag breal bimag
a = areal + 1i*aimag;
b = breal + 1i*bimag;
%residue = sum((fy - a*exp(b*fx)).^2);
residue = norm(fy - a*exp(b*fx));
rfun = matlabFunction(residue, 'vars', {[areal, aimag, breal, bimag]});
[best, fval] = fmincon(rfun, [-.1 -.1 1e-5 1e-5], [], [], [], [], [-1e6 -1e6 -700 -700], [1e6 1e6 700 700])
a = best(1) + 1i*best(2)
b = best(3) + 1i*best(4)
y = a*exp(b*x)
vpa(y)
scatter(fx, fy);
hold on
fplot(real(y), [min(fx), max(fx)])
hold off
Coefficients not quite as large, but the plot is still flat.
If you try to fit a*exp(b*x) using fmincon and using only real values, Yes, you get an answer, but the residue is large
More Answers (0)
See Also
Categories
Find more on Fit Postprocessing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!