MATLAB 多项式拟合选择性幂

MATLAB polynomial fit selective powers

我有 2 个向量 x 和 y,我想在 MATLAB 中将多项式拟合为 y = f(x)
我本可以使用 polyfit。但是,我只想拟合多项式的选择性幂项。例如,y = f(x) = a*x^3 + b*x + c。请注意,我在那里没有 x^2 项。 MATLAB 中是否有任何内置函数可以实现此目的?
我不确定是否简单地忽略 MATLAB 为 x^2 给出的系数是否与拟合没有 x^2 项的多项式相同。

听起来你有拟合工具箱,只想删除一个可能的系数。如果是这样的话,这里有一个方法可以做到。

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

如果你没有曲线拟合工具箱(见@thewaywewalk的评论),反正也好用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

给予

ans =
    4.9799
    2.0211
    6.9980

注意"simply ignoring the coefficient that MATLAB gives for x^2"绝对不是"same as fitting the polynomial without x^2 term"。

在最近的 Matlab 版本中,您可以通过 select 点击 APPS 选项卡然后点击 Curve Fitting Tool.

使用 GUI 轻松完成此操作

比如我定义:

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

然后我 select 这些变量在工具中作为 X dataY data,我选择一个 custom equation 定义为 a*x^3 + b*x + c。结果是: