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!
0 件のコメント
採用された回答
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 件のコメント
Matt J
2020 年 9 月 5 日
You're quite welcome, but please Accept-click the answer if you consider your question resolved.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File 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!