# Matlab fitting an anonymous function

30 views (last 30 days)
Tim on 14 Apr 2014
Edited: Matt J on 13 Oct 2021
I have fitted my data using the matlab build in fitting function, such as 'exp2'. Since those build in functions did not work perfectly for all of my data, I tried using anonymous functions to fit my data. I could not get good results, so i tried to add the 'exp2' function as an anonymous function and compare it to the original build in 'exp2' function:
xdata = [5 10 20 40 80 100 150 200 250];
ydata = [2 6 12 20 30 40 50 70 100];
% My function
fitfun = @(a,b,c,d,x) a*exp(b*x) + c*exp(d*x);
[f,goodness] = fit( xdata, ydata, fitfun, fitoptions('exp2'))
coeffs = coeffvalues(f)
In combination with:
% Exponential function
[f2,goodness] = fit( xdata, ydata, 'exp2')
coeffs = coeffvalues(f2)
The results were almost always very different and the fit of the anonymous function was almost always very crappy. The fit with the build in 'exp2' function was fine.
So I want to know:
• 1) What is the essential different between my anonymous 'exp2' function and the build in 'exp2' function
• 2) What do I have to do to get good fitting values with my anonymous functions? Not only this one, but also other functions I want to try.
Royi Avital on 14 Apr 2014
What do you mean "he results were almost always very different"?
Given a vectors the algorithm should be deterministic.
Tim on 12 Jun 2014
Ah! I almost forgot about my question. So, I basically get a random fit if I do not provide my own a start point. This fit can look very similar to the build in one, but it could also be one big mess. I want to know why this difference occurs, since I use the same fitoptions and fit-function as the build in 'exp2' fit.

Matt J on 13 Oct 2021
Edited: Matt J on 13 Oct 2021
The difference is that, with an anonymous function, you now have the responsibility of providing the StartPoint for the iterative search in the fitoptions. If you don't, then fit() will interpret the model as a custom model and default to a random StartPoint (which would explain why the fits you're getting are so poor). See also,
Tim on 13 Oct 2021
Matt J on 13 Oct 2021
Edited: Matt J on 13 Oct 2021

Julia Gala on 13 Oct 2021
Hi Tim,
I just came accross this, it has been years, so you may never check this. In your question, you don't share the fitoptions you are using for your fit. I believe the main differences will be in the fitoptions here, and that is likely why you are getting different fitting results with the same definition of functions. If you are still interested on this, I would run the anonymous function vs the built in function with the same fitting options (add fitting options to the built in function). Feel free to share what you get.
Sincerely,
Julia

### Categories

Find more on Get Started with Curve Fitting Toolbox 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!