Using an anonymous function in lsqcurvefit function

5 次查看(过去 30 天)
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!

采纳的回答

Matt J
Matt J 2020-9-5
编辑:Matt J 2020-9-5
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 个评论
Jason
Jason 2020-9-5
编辑:Jason 2020-9-5
So it is about syntax issue. I see. Thank you so much for your thorough explanation!
Matt J
Matt J 2020-9-5
You're quite welcome, but please Accept-click the answer if you consider your question resolved.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with Curve Fitting Toolbox 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by