I have 2 vectors x and y to which I want to fit a polynomial as y = f(x)
in MATLAB.
I could have used polyfit
. However, I want to fit only selective power terms of the polynomial. For example, y = f(x) = a*x^3 + b*x + c
. Notice that I don't have the x^2
term in there. Is there any built-in function in MATLAB to achieve this?
I am not sure if simply ignoring the coefficient that MATLAB gives for x^2
is same as fitting the polynomial without x^2
term.
It sounds like you have the fitting toolbox and want to just remove a possible coefficient. If that's the case, here's a way to do it.
%What is the degree of the polynomial (cubic)
polyDegree = 3;
%What powers do you want to skip (x^2 and x)
skipPowers = [2, 1];
%This sets up the options
opts = fitoptions( 'Method', 'LinearLeastSquares' );
%All coefficients of degrees not specified between x^n and x^0 can have any value
opts.Lower = -inf(1, polyDegree + 1);
opts.Upper = inf(1, polyDegree + 1);
%The coefficients you want to skip have a range from 0 to 0.
opts.Lower(polyDegree + 1 - skipPowers) = 0;
opts.Upper(polyDegree + 1 - skipPowers) = 0;
%Do the fit using the specified polynomial degree.
[fitresult, gof] = fit( x, y, ['poly', num2str(polyDegree)] , opts );