tumchaaditya
tumchaaditya

Reputation: 1297

MATLAB polynomial fit selective powers

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.

Upvotes: 2

Views: 1380

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112659

In recent Matlab versions you can do it easily with a GUI by selecting the APPS tab and then the Curve Fitting Tool.

For example, I define:

x = 1:10;
y = x + randn(1,10);

I then select those variables as X data, Y data in the tool and I choose a custom equation defined as a*x^3 + b*x + c. The results are:

enter image description here

Upvotes: 0

Ramashalanka
Ramashalanka

Reputation: 8854

If you don't have the curve fitting tool box (see @thewaywewalk's comment), or anyway, it is easy to use mldivide:

x=rand(10,1);                  % your x data
y=5*x.^3+2*x+7+rand(10,1)*.01; % some y data with noise
[x.^3 x ones(size(x))]\y       % least squares solve to y = a*x^3 + b*x + c

gives

ans =
    4.9799
    2.0211
    6.9980

Note that "simply ignoring the coefficient that MATLAB gives for x^2" is definitely not the "same as fitting the polynomial without x^2 term".

Upvotes: 2

user1543042
user1543042

Reputation: 3440

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 );

Upvotes: 1

Related Questions