% 最小二乘法拟合 B=1;
clear;clc;
wt=0:pi/6:5*pi/6;
B=sin(wt);
H=[280,400,720,800,400,-150];
T0=[0.01,0.01,0.01,0.01];
fun=inline('1*(1/u(1)*sin(wt+u(3))+1/u(2)*sin(3*wt+u(4)))','u','wt'); % 定义函数
[u1,r,J]=nlinfit(wt,H,fun,T0);
% wt,H为原始数据,fun是在M文件中定义的函数,T0是函数中参数的初始值;
% ui为参数的最优值,r是各点处的拟合残差,J为雅克比矩阵的数值.
R=sum(r.^2);%误差平方和
T=0:0.1:2*pi;
BB=sin(T);
HH=1*(1/u1(1,1)*sin(T+u1(1,3))+1/u1(1,2)*sin(3*T+u1(1,4))); %根据b1写出具体函数
plot(H,B,'-*',HH,BB,'-or');
axis([-1000,1000,-1.2,1.2])
annotation('arrow',[0.178 0.876],...
[0.516 0.516]);
annotation('arrow',[0.5173 0.517],...
[0.154 0.902]);
xlabel('H'), ylabel('B'),title('B-H'); |