--- title: 數學軟體實作 - Polyfit tags: 2020 Fall - 數學軟體實作 GA: G-77TT93X4N1 --- # Lecture - `polyfit` Matlab `polyfit` 這指令可以在給定資料點的情況下找到一條最佳的多項式. 用法很簡單, X 以及 Y 是資料點的 $x$ 跟 $y$ 座標, N 則是多項式次數, 則以下指令可以找出此 N 次多項式的係數: ``` P = polyfit(X,Y,N); ``` 若想要求出此多項式在某些點的值, 則可以用 `polyval` 指令: ``` f = polyval(p,x); ``` 其中 x 是一個向量, 表示我們要在哪些 $x$ 點上求多項式的值. 而求出的 f 也是個向量, 其值為 f(x). 比如說 Matlab `polyfit` 中的例子: ```matlab= % Fit a polynomial p of degree 1 to the (x,y) data: x = 1:50; y = -0.3*x + 2*randn(1,50); p = polyfit(x,y,1); % Evaluate the fitted polynomial p and plot: f = polyval(p,x); plot(x,y,'o',x,f,'-') legend('data','linear fit') ``` --- #### Exercise 在平面上給定點 $(0,0), (1,0), (2,0), (2,1), (3,1), (3,2),$ 試找出兩多項式 $(P_1(t), P_2(t))$ 通過這些點. $$ \gamma(t) = (x(t), y(t)), \quad x(t) = a_0 + a_1t + a_2 t^2+\cdots, \quad y(t) = b_0 + b_1t + b_2 t^2+\cdots, $$ ```matlab= % data points (x,y) x = [0 1 2 2 3 3]; y = [0 0 0 1 1 2]; % 參數式中座標 t t = [0 1 2 3 4 5]; % Fit a polynomial to x and y seperately to obtain x(t) and y(t) px = polyfit(t, x, 5); py = polyfit(t, y, 5); % 畫出 gamma(t)=(x(t), y(t)) tt = linspace(0,5); fx = polyval(px, tt); fy = polyval(py, tt); plot(x, y, 'o-', fx, fy) ``` ---