Creating a polynomial fit expression using just the order number

Hello. Im performing a fit to data using e.g a 3rd order polynomial and the expresion below. For cases when i want e.g a 4th or 5th order fit, rather than use a switch / case approach is there a way to construct the expression below simply by passing in n the polynomial order?

a123 = [x.^3, x.^2, x]\y;

 採用された回答

dpb
dpb 2025 年 11 月 18 日
編集済み: dpb 2025 年 11 月 18 日

1 投票

c=x.^[n:-1:1]\y;
I presume leaving off the intercept is intentional? Otherwise, there's polyfit

5 件のコメント

Jason
Jason 2025 年 11 月 18 日

Thanks

dpb
dpb 2025 年 11 月 19 日
If I were doing this in anger, I'd probably couch it as an anonymous function..
polyN=@(x,y,n)x.^[n:-1:1]\y;
Jason
Jason 2025 年 11 月 19 日
編集済み: Jason 2025 年 11 月 19 日
I need to be able to "force fit" so it passes through a certain point
ax=app.UIAxes3;
[x,y] = getDataFromGraph(app,ax,1); % My function to extract x,y data
hold(ax,"on");
D=[x,y];
D=rmmissing(D); % Remove rows with any NaNs or missing data
x=D(:,1); y=D(:,2);
% Force polyfit thru first point
x0=x(1,1);
y0=y(1,1);
ReportMessage(app,['Forced Fit Thru Point: (',num2str(x0),', ',num2str(y0),')'])
% assume model of the form y=a1*x^3+a2*x^2+a3*x
% we can fit simply as P=[a123;0]
% but now if we want to force the model it so passes thru x0,y0
% essentially have to fit the model (just transfor like this)
% y-y0=a1*(x-xo)^3+a2(x-x0)^2+a3(x-x0)
% so when x==x0, y==y0
xtr=x-x0;
% acoeffs=[xtr.^5,xtr.^4,xtr.^3,xtr.^2,xtr]\(y-y0) %acoeffs=[xtr.^7,xtr.^6,xtr.^5,xtr.^4,xtr.^3,xtr.^2,xtr]\(y-y0)
acoeffs=[xtr.^7,xtr.^6,xtr.^5,xtr.^4,xtr.^3,xtr.^2,xtr]\(y-y0);
%Evaluation of the model is easy, you can still use polyval
% just rememeber to subtract x0 from x first
P=[acoeffs;y0];
ypred=polyval(P,x-x0);
plot(ax,x,ypred,'y--','LineWidth',2);
dpb
dpb 2025 年 11 月 19 日
With a 7th order polynomial, are you forcing it through a set of points, maybe? Would a spline be an alternative?
Torsten
Torsten 2025 年 11 月 19 日
編集済み: dpb 2025 年 11 月 20 日
xtr=x-x0;
% acoeffs=[xtr.^5,xtr.^4,xtr.^3,xtr.^2,xtr]\(y-y0) %acoeffs=[xtr.^7,xtr.^6,xtr.^5,xtr.^4,xtr.^3,xtr.^2,xtr]\(y-y0)
acoeffs=[xtr.^7,xtr.^6,xtr.^5,xtr.^4,xtr.^3,xtr.^2,xtr]\(y-y0);
will give you a polynomial that passes through (x0,y0), but will have a constant term - thus will no longer be of the form you used earlier.
Thus the property of passing through (x0,y0) is payed by losing the property of passing through (0,0).

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangePolynomials についてさらに検索

製品

リリース

R2024b

タグ

質問済み:

2025 年 11 月 18 日

編集済み:

dpb
2025 年 11 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by