Matlab 对于参数N,是否可以使用范围而不是标量的多边形拟合?
函数需要多项式次数Matlab 对于参数N,是否可以使用范围而不是标量的多边形拟合?,matlab,range,octave,Matlab,Range,Octave,函数需要多项式次数n的标量值,例如 P = polyfit(X, Y, 3) 这表明应使用for循环来确定拟合同一曲线的多项式范围(比如2阶到4阶): % Fit a given curve with a series of polynomials % of given degrees X = 1:6; % Range of x in the sample Y0 = [10, 11, 21, 2, 3, 7]; % Sample DEG = 2:6; % Degrees to use for
n
的标量值,例如
P = polyfit(X, Y, 3)
这表明应使用for
循环来确定拟合同一曲线的多项式范围(比如2阶到4阶):
% Fit a given curve with a series of polynomials
% of given degrees
X = 1:6; % Range of x in the sample
Y0 = [10, 11, 21, 2, 3, 7]; % Sample
DEG = 2:6; % Degrees to use for polynomials
plot(X, Y0) % Plot sample for reference
for n = DEG
hold on
P = polyfit(X, Y0, n); % Fitting polynomial, degree n
Y = polyval(P, X); % Compute y for this polynomial
plot(X, Y)
endfor
有没有办法通过直接在函数中使用range DEG来简化此代码并将其转换为“all array”?我尝试了几种不同的polyfit(X,Y0,DEG)
,但倍频程一直告诉我:
error: polyfit: N must be a non-negative integer
感谢您的帮助。这就是
arrayfun
的用途:
octave:1> X = 1:6;
octave:2> Y0 = [10, 11, 21, 2, 3, 7];
octave:3> DEG = 2:6;
octave:4> arrayfun (@(n) polyfit (X, Y0, n), DEG, "UniformOutput", false)
ans =
{
[1,1] =
-0.37500 0.96786 11.30000
[1,2] =
1.0833 -11.7500 35.3095 -16.0000
[1,3] =
0.43750 -5.04167 17.43750 -18.94048 15.50000
[1,4] =
-1.2750 22.7500 -150.9583 456.2500 -612.7667 296.0000
[1,5] =
-0.31438 5.32693 -32.26604 80.10905 -54.29889 -58.20494 69.64828
}
我认为没有,但也没有真正的理由不实际循环。
polyfit
的输出是长度为n+1
的行向量。如果n
更改,输出将具有不同的大小。原则上,输出可以作为单元数组返回,但是Matlab的函数通常不包含这种复杂性(而且函数中仍然隐藏着一个for
循环)。将大于2次的多项式拟合到数据([X,Y0]
)看起来很像过度拟合,而次数>=5将是插值。