polyfit
函数需要多项式度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
有没有办法简化此代码并将其转换为'所有数组'通过在函数中直接使用范围DEG?我在polyfit(X, Y0, DEG)
附近尝试了几种变体,但Octave一直告诉我:
error: polyfit: N must be a non-negative integer
任何帮助表示感谢。
答案 0 :(得分:1)
这是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
}