MATLAB: How to do a polynomial fit to a dataset with an excluded term

Curve Fitting Toolboxexcluded"fitfitlmfitoptionsfittypehigh ordermatrixpolynomialStatistics and Machine Learning Toolboxtermterms

How do I obtain a high-order polynomial fit to some data, but with a term excluded? For example:
y ~ C0 + C1*x + C2*x^2 + C4*x^4 % Note the 3rd-order term is missing

Best Answer

We can meet this requirement using either option 1 or option 2, discussed below. In either case, we have used the data sample "carsmall," which comes with the Statistics and Machine Learning Toolbox.
Option 1: Using "fit"
Below is an example that demonstrates the required fit. This workflow requires the Curve Fitting Toolbox:
load carsmall
% remove NaN values:


nanidx = find(isnan(Horsepower));
Horsepower(nanidx) = [];
Weight(nanidx) = [];
fo = fitoptions('Method','NonlinearLeastSquares', 'Normalize', 'on', 'Robust', 'LAR','StartPoint',[1 1 1 1]);
ft = fittype('C0+C1*x^(n-3)+C2*x^(n-2)+C4*x^n','problem','n','options',fo);
[curve2,gof2] = fit(Weight,Horsepower,ft,'problem',4);
plot(curve2,Weight,Horsepower)
Result using fit:
For options on fine-tuning the curve fitting, please see the below documentation links:
"fitoptions":
"fittype":
"fit":
Option 2: Using "fitlm"
Below is an example that demonstrates the required fit using a term matrix. This workflow requires the :
load carsmall
% remove NaN values:
nanidx = find(isnan(Horsepower));
Horsepower(nanidx) = [];
Weight(nanidx) = [];
% Create a "terms matrix" to select which terms are used in the regression.
% A formula like C0 + C1*X + C2*X^2 + C4*x^4 has 4 terms, so the terms
% matrix has 4 rows:
terms1 = [0 0]; % constant term
terms2 = [1 0]; % X^1
terms3 = [2 0]; % X^2
terms4 = [4 0]; % X^4
terms = [terms1; terms2; terms3; terms4];
% create the LinearModel object:
lm = fitlm(Weight,Horsepower,terms,'RobustOpts','on'); % fit Horsepower as a function of C0 + C1*Weight + C2*Weight^2 + C4*Weight^4
plot(lm)
Here is an alternative way to achieve the required fit, without using a terms matrix.
load carsmall
% remove NaN values:
nanidx = find(isnan(Horsepower));
Horsepower(nanidx) = [];
Weight(nanidx) = [];
lm = fitlm(Weight,Horsepower,'y~x1^4 - x1:x1:x1');
plot(lm)
Result using fitlm:
For more information, please look into the below documentation link on "fitlm":