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;

 Réponse acceptée

dpb
dpb le 18 Nov 2025
Modifié(e) : dpb le 18 Nov 2025
c=x.^[n:-1:1]\y;
I presume leaving off the intercept is intentional? Otherwise, there's polyfit

5 commentaires

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 le 19 Nov 2025
Modifié(e) : Jason le 19 Nov 2025
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);
With a 7th order polynomial, are you forcing it through a set of points, maybe? Would a spline be an alternative?
Torsten
Torsten le 19 Nov 2025
Modifié(e) : dpb le 20 Nov 2025
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).

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Polynomials dans Centre d'aide et File Exchange

Produits

Version

R2024b

Question posée :

le 18 Nov 2025

Modifié(e) :

dpb
le 20 Nov 2025

Community Treasure Hunt

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

Start Hunting!

Translated by