Matlab多項式


MATLAB表示多項式為包含由下降冪排列的係數的行向量。 例如,方程式

可以表示為 -

p = [1 7 0 -5 9];

評估計算多項式

多值函式用於評估計算指定值的多項式。 例如,要評估前面的多項式p,在x = 4,可使用以下程式碼 -

p = [1 7 0  -5 9];
polyval(p,4)

MATLAB執行上述語句返回以下結果 -

ans = 693

MATLAB還提供polyvalm函式用於評估矩陣多項式。 矩陣多項式是以矩陣為變數的多項式。

例如,下面建立一個方陣X並評估求值多項式p,在X -

p = [1 7 0  -5 9];
X = [1 2 -3 4; 2 -5 6 3; 3 1 0 2; 5 -7 3 8];
polyvalm(p, X)

MATLAB執行上述程式碼語句返回以下結果 -

ans =
        2307       -1769        -939        4499
        2314       -2376        -249        4695
        2256       -1892        -549        4310
        4570       -4532       -1062        9269

計算多項式的根

roots函式計算多項式的根。 例如,要計算多項式p的根,可參考以下語法 -

p = [1 7 0  -5 9];
r = roots(p)

MATLAB執行上述程式碼語句返回以下結果 -

r =
  -6.8661 + 0.0000i
  -1.4247 + 0.0000i
   0.6454 + 0.7095i
   0.6454 - 0.7095i

poly函式是roots函式的逆,並返回到多項式係數。 例如 -

p = [1 7 0  -5 9];
r = roots(p)
p2 = poly(r)

MATLAB執行上述程式碼語句返回以下結果 -

Trial>> p = [1 7 0  -5 9];
r = roots(p)
p2 = poly(r)

r =

  -6.8661 + 0.0000i
  -1.4247 + 0.0000i
   0.6454 + 0.7095i
   0.6454 - 0.7095i


p2 =

    1.0000    7.0000    0.0000   -5.0000    9.0000

多項式曲線擬合

polyfit函式用來查詢一個多項式的係數,它符合最小二乘法中的一組資料。 如果xy包含要擬合到n度多項式的xy資料的兩個向量,則得到通過擬合資料的多項式,參考程式碼 -

p = polyfit(x,y,n)

範例

建立指令碼檔案並鍵入以下程式碼 -

x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67];  %data
p = polyfit(x,y,4)   %get the polynomial
% Compute the values of the polyfit estimate over a finer range, 
% and plot the estimate over the real data values for comparison:
x2 = 1:.1:6;          
y2 = polyval(p,x2);
plot(x,y,'o',x2,y2)
grid on

MATLAB執行上述程式碼語句返回以下結果 -

Trial>> x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67];  %data
p = polyfit(x,y,4)   %get the polynomial
% Compute the values of the polyfit estimate over a finer range, 
% and plot the estimate over the real data values for comparison:
x2 = 1:.1:6;          
y2 = polyval(p,x2);
plot(x,y,'o',x2,y2)
grid on

p =

    4.1056  -47.9607  222.2598 -362.7453  191.1250

同時還輸出一個圖形 -