Using an anonymous function in lsqcurvefit function

조회 수: 7 (최근 30일)
Jason
Jason 2020년 9월 5일
댓글: Matt J 2020년 9월 5일
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에서 Downloads에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by