Using an anonymous function in lsqcurvefit function
6 views (last 30 days)
Show older comments
Hello,
I am trying to learn how to use an anonymous function in lsqcurvefit. While I was reading documentation on lsqcurvefit I just a question on the format. The below is a simple example.
Here is the observations (input).
xdata = ...
[0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3];
ydata = ...
[455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];
Fit the model using the starting point x0 = [100,-1].
x0 = [100,-1];
x = lsqcurvefit(@(x,xdata) x(1)*exp(x(2)*xdata),x0,xdata,ydata)
My question is why should it be
x = lsqcurvefit(@(x,xdata) x(1)*exp(x(2)*xdata),x0,xdata,ydata)
instead of
x = lsqcurvefit(@(x) x(1)*exp(x(2)*xdata),x0,xdata,ydata)
I can follow the flow. But I don't understand why I should input both x and xdata into the anonymous function as @(x,xdata). This might sound naive but xdata is listed as input after x0 in the lsqcurvefit already, so I thought lsqcurvefit would know what xdata is in the anonymous function. If I run @(x) instead of @(x,data), I got this error message: Too many input arguments. Could someone please explain this?
Thank you!
0 Comments
Accepted Answer
Matt J
on 5 Sep 2020
Edited: Matt J
on 5 Sep 2020
I believe the reason is that in curve fitting scenarios you will normally want to do things like this:
fun = @(x,xdata) x(1)*exp(x(2)*xdata);
x_optimal = lsqcurvefit(fun,x0,xdata,ydata)
hold on
plot(xdata,fun(x_optimal,xdata),'x')
fplot(@(z)fun(x_optimal,z),xlim);
hold off
In other words, when you are performing the curve fit, you usually want to view the model function as a function of the unknown parameters with xdata held fixed. However, after you have performed the fit and obtained an x_optimal, the opposite is true. You will now want to view the model function as a function of xdata with fixed x=x_optimal, and query the function at various alternative xdata values (for plotting and other purposes). The makers of lsqcurvefit recognized these different use cases and decided that having you work in terms of a two-argument model function would be the user-friendliest way to accommodate them.
4 Comments
Matt J
on 5 Sep 2020
You're quite welcome, but please Accept-click the answer if you consider your question resolved.
More Answers (0)
See Also
Categories
Find more on Downloads 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!