我有这个 Matlab 代码,可以从一组数据创建正弦曲线拟合
data = importdata('analisipicco.txt') ;
x = data(:,1) ; y = data(:,2) ;
yu = max(y);
yl = min(y);
yr = (yu-yl); % Range of ‘y’
yz = y-yu+(yr/2);
zx = x(yz .* circshift(yz,1) <= 0); % Find zero-crossings
per = 2*mean(diff(zx)); % Estimate period
ym = mean(y); % Estimate offset
fit = @(b,x) b(1).*(sin(2*pi*x./b(2) + 2*pi/b(3))) + b(4); % Function to fit
fcn = @(b) sum((fit(b,x) - y).^2); % Least-Squares cost function
s = fminsearch(fcn, [yr; per; -1; ym]); % Minimise Least-Squares
xp = linspace(min(x),max(x));
xlabel("passi motore");
ylabel("intensità (u.a.)");
figure(1)
plot(x,y,'o', xp,fit(s,xp), 'r')
grid
其中输出参数向量 s(函数中的 b)的元素为:
s(1):正弦波幅度(单位为y)
s(2):周期(以x为单位)
s(3):相位(相位为s(2)/(2*s(3)),单位为x)
s(4):偏移量(以y为单位)
确认这是我的数据集:
-200 183966
-192 189734
-184 195724
-176 201663
-168 207557
-160 213278
-152 219000
-144 224677
-136 229500
-128 236024
-120 241968
-112 247787
-104 252963
-96 257491
-88 261967
-80 267373
-72 273494
-64 278599
-56 281476
-48 282610
-40 283097
-32 283839
-24 284971
-16 286169
-8 287164
0 287968
8 288561
16 288626
24 288107
32 286967
40 285132
48 282828
56 279847
64 276296
72 272299
80 268080
88 263564
96 258926
104 254052
112 248894
120 243694
128 238177
136 232665
144 227143
152 221959
160 216874
168 211678
176 206540
184 201537
192 196748
200 192091
该程序运行良好,但我的问题是关于查找参数和协方差上的错误,我可以实现矩阵方法并查找协方差矩阵,但我不知道如何编写代码。
我是Matlab新手,所以我想问是否有一些函数可以计算误差。
提前谢谢你:))
是的,有一个专门用于最小二乘法的函数。它称为 lsqcurvefit 第三个输出参数给出您想要的残差(误差)。见
help lsqcurvefit
就你而言
initial_guess = [yr; per; -1; ym];
[s, resnorm, residual] = lsqcurvefit(fit, initial_guess, x, y);
plot(x, residual)
对于协方差,除了从雅可比行列式(这是 lsqcurvefit 的第 7 个输出参数)计算它之外,我没有找到任何方法:
[s, resnorm, residual, flag, output, lambda, jacobian] = lsqcurvefit(fit, initial_guess, x, y);
covariance = inv(jacobian' * jacobian) * resnorm / (length(y) - length(s));
请检查该协方差公式是否是您要计算的公式。
我希望这个答案很好。