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

7 visualizaciones (últimos 30 días)
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

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 13 de Abr. de 2023
Editada: MathWorks Support Team el 14 de Abr. de 2023
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":
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 termterms2 = [1 0]; % X^1terms3 = [2 0]; % X^2terms4 = [4 0]; % X^4terms = [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":

Más respuestas (0)

Categorías

Más información sobre Linear and Nonlinear Regression en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by