在影像處理裡做線條轉換時,曲線擬合是個重點環節。本文把 Matlab 中直線擬合與曲線擬合的常見寫法完整梳理一遍。
fittype 用來建立曲線或曲面的擬合模型物件,基本語法:
ffun = fittype(libname)
ffun = fittype(expr)
ffun = fittype({expr1,...,exprn})
ffun = fittype(expr, Name, Value,...)
ffun = fittype({expr1,...,exprn}, Name, Value,...)
線性擬合的形式是:
coeff1 * term1 + coeff2 * term2 + coeff3 * term3 + ...
其中 coefficient 是係數,而每個 term 都必須是 x 的一次項。這一條是判斷「線性」與否的關鍵:所謂線性指的是對係數而言線性,而不是外觀看起來像直線。
做法一,用 polyfit:
x = [1, 1.5, 2, 2.5, 3]; y = [0.9, 1.7, 2.2, 2.6, 3]; p = polyfit(x, y, 1); x1 = linspace(min(x), max(x)); y1 = polyval(p, x1); plot(x, y, '*', x1, y1);
結果 p = 1.0200 0.0400,也就是 y = 1.0200x + 0.0400。
做法二,用 fittype 搭配 fit:
x = [1; 1.5; 2; 2.5; 3];
y = [0.9; 1.7; 2.2; 2.6; 3];
p = fittype('poly1');
f = fit(x, y, p);
plot(f, x, y);
輸出會直接告訴你模型形式與 95% 信賴區間:
Linear model Poly1: f(x) = p1*x + p2 Coefficients (with 95% confidence bounds): p1 = 1.02 (0.7192, 1.321) p2 = 0.04 (-0.5981, 0.6781)
做法一,用 cell array 指定各項:
x = [1; 1.5; 2; 2.5; 3];
y = [0.9; 1.7; 2.2; 2.6; 3];
EXPR = {'x', 'sin(x)', '1'};
p = fittype(EXPR);
f = fit(x, y, p);
plot(f, x, y);
Linear model: f(x) = a*x + b*sin(x) + c Coefficients (with 95% confidence bounds): a = 1.249 (0.9856, 1.512) b = 0.6357 (0.03185, 1.24) c = -0.8611 (-1.773, 0.05094)
做法二,直接寫表達式並指定自變數:
p = fittype('a*x+b*sin(x)+c', 'independent', 'x');
f = fit(x, y, p);
plot(f, x, y);
係數結果與做法一完全相同。這裡 Matlab 會跳出一個警告:未提供起始點,因此隨機選了一個。對非線性求解來說,起始點會影響收斂,資料規模大或模型複雜時建議用 'StartPoint' 明確指定。
x = [1; 1.5; 2; 2.5; 3];
y = [0.9; 1.7; 2.2; 2.6; 3];
p = fittype('a*x.^2+b*x+c', 'independent', 'x');
f = fit(x, y, p);
plot(f, x, y);
注意這裡必須寫 x.^2 而非 x^2,因為要對向量做逐元素平方。輸出:
General model: f(x) = a*x.^2+b*x+c Coefficients (with 95% confidence bounds): a = -0.2571 (-0.5681, 0.05386) b = 2.049 (0.791, 3.306) c = -0.86 (-2.016, 0.2964)
做法二用匿名函式,還能示範「固定某個參數」與「預測某個參數」兩種玩法:
% 固定 c = 0 c = 0; p1 = fittype(@(a, b, x) a*x.^2 + b*x + c); f1 = fit(x, y, p1); % 固定 c = 1 c = 1; p2 = fittype(@(a, b, x) a*x.^2 + b*x + c); f2 = fit(x, y, p2); % 讓 c 也被擬合 p3 = fittype(@(a, b, c, x) a*x.^2 + b*x + c); f3 = fit(x, y, p3); % 結果視覺化 scatter(x, y); % 散點 plot(f1, 'b:*'); % 藍色 hold on plot(f2, 'g:+'); % 綠色 hold on plot(f3, 'm:*'); % 紫色 hold off
如果只是多項式,polyfit/polyval 更輕快,也不會有隨機起始點的問題。fit 的價值在於三件事:能自訂任意模型、會自動給出信賴區間與 goodness of fit 統計(可用 [f, gof] = fit(...) 取得 R²、RMSE 等),以及產出的 fit 物件可以直接 plot 與 integrate。模型一旦不是多項式,就只能走 fit 這條路。