How to use use an anonymous function to fit data based on the fittype and fit functions.

5 ビュー (過去 30 日間)
payam samadi
payam samadi 2022 年 6 月 24 日
コメント済み: payam samadi 2022 年 6 月 27 日
Hi there,
I have some sort of data point and I want to use an anonymous function to fit this data based on the fittype and fit functions.
Also, the function is look like this:
F(x)=a*x^2+b*x+c+d*diff(x^2)+e*diff(x)
Any suggestions?
Thanks

採用された回答

William Rose
William Rose 2022 年 6 月 24 日
I think the manual page examples for this are pretty good.
a=1; b=2; c=-1; d=-2; e=3;
xdata=-3:.03:3;
%ydata=a*xdata(2:end)+b*xdata(2:end).^2+c+d*diff(xdata)+e*diff(xdata).^2+randn(1,length(xdata)-1);
fun=@(p,x) p(1)*x(2:end)+p(2)*x(2:end).^2+p(3)+p(4)*diff(x)+p(5)*diff(x).^2;
yclean=fun([a,b,c,d,e],xdata);
ydata=yclean+randn(1,length(xdata)-1);
p0=[1,1,1,1,1];
p = lsqcurvefit(fun,p0,xdata,ydata)
Local minimum possible. lsqcurvefit stopped because the final change in the sum of squares relative to its initial value is less than the value of the function tolerance.
p = 1×5
1.0099 2.0178 -0.8965 -3.6526 -48.7815
yfit=fun(p,xdata);
plot(xdata(2:end),yclean,'-r',xdata(2:end),ydata,'rx',xdata(2:end),yfit,'-b')
legend('Clean Data','Noisy Data','Best Fit')
The fit to the data is excellent, and the two curves are so close that they overlap, but the fitted parameters do not match the original parameters. This is because the input diff(x) is a constant, and therefore is not independent of the "c" term, and the input diff(x^2) is a straight line, and therefore not indepndent of the "a" term.
Try this. Good luck.
  7 件のコメント
payam samadi
payam samadi 2022 年 6 月 27 日
Many thanks, I think that work fine for me.
Best

サインインしてコメントする。

その他の回答 (2 件)

Denis
Denis 2022 年 6 月 25 日
Thanks for post, me need it!

Walter Roberson
Walter Roberson 2022 年 6 月 24 日
There is no chance of fitting that function.
fit() and fittype() pass in numeric data, and diff() of numeric data is always smaller than the original data. Therefore your a*x^2+b*x+c is an incompatible size to be added to d*diff(x^2)+e*diff(x)
It might make sense to rewrite in terms of gradient()
Does diff(x) happen to be constant (points are equally spaced)? If so then I suspect you can rewrite the formulas for more efficient fitting
  2 件のコメント
payam samadi
payam samadi 2022 年 6 月 25 日
Thanks for your answer,
Yes, I can confirm that the equation is the same that I mentioned.
Also, I add the data sets, which may can be useful.

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by