x = 1:100;
y = -0.3*x + 2*randn(1,100);
[p,S] = polyfit(x,y,1)
p = 1×2
-0.3142 0.9614
S = struct with fields:
R: [2×2 double]
df: 98
normr: 22.7673
rsquared: 0.9407
计算以 p 为系数的一次多项式在 x 中各点处的拟合值。将误差估计结构体指定为第三个输入,以便 polyval 计算标准误差的估计值。标准误差估计值在 delta 中返回。
[y_fit,delta] = polyval(p,x,S);
绘制原始数据、线性拟合和 95% 预测区间 。
plot(x,y,'bo')
hold on
plot(x,y_fit,'r-')
plot(x,y_fit+2*delta,'m--',x,y_fit-2*delta,'m--')
title('Linear Fit of Data with 95% Prediction Interval')
legend('Data','Linear Fit','95% Prediction Interval')