非线性曲线拟合和多项式曲线拟合

非线性曲线拟合和多项式曲线拟合

  • 1.建模 2.非线性拟合求参数 3.完成拟合
  • Fitting.m

1.建模 2.非线性拟合求参数 3.完成拟合

非线性曲线拟合和多项式曲线拟合_第1张图片
非线性曲线拟合和多项式曲线拟合_第2张图片
非线性曲线拟合和多项式曲线拟合_第3张图片
非线性曲线拟合和多项式曲线拟合_第4张图片

Fitting.m

%% =================================================
%% 非线性曲线拟合和多项式曲线拟合程序
%% Author@xclRobotLife(凌寒画家)2019.1.23 
%% =====================曲线拟合=====================
function Fitting%nonlinear
data1=[5.1852 5.1722 5.1609 5.1466 5.1284 5.1084 5.0696 4.7772 3.5199 2.5902   2.3824 2.2447 2.2057 2.0723];
data2=[ 1.9075 2.0061 1.9083 2.0341 2.0145 2.2557 2.1430 2.3352 3.6835 4.7761 4.8588 5.5268 5.7353 5.8707];
n=length(data1);
%求参数
P1=[2.6 -2 9 18 1];%初始参数P1=[1 2 3 4 5];
[PR1,SSD1]=lsqcurvefit(@fun,P1,1:n,data1);
P2=[2.6 -2 9 18 1];
[PR2,SSD2]=lsqcurvefit(@fun,P2,1:n,data2);
fprintf('拟合误差平方和均值SSD------data1:%f,data2:%f\n',SSD1,SSD2);


%Figure
x=1:n;
xn=1:0.1:18;%稠密调节
figure(1)
plot(x,data1,'-ko','MarkerFace','g'),hold on;
plot(xn,PR1(1)*(tansig(-PR1(2)*(xn-PR1(3))/PR1(4))+PR1(5)),'-kx','MarkerFace',[153 0 153]/255),hold on;
plot(x,data2,'-ks','MarkerFace','r'),hold on;
plot(xn,PR2(1)*(tansig(-PR2(2)*(xn-PR2(3))/PR2(4))+PR2(5)),'-kd','MarkerFace',[237 177 32]/255),hold on;
set(gca,'Ygrid','on');                  
legend('Testing data1','Fitting data1','Testing data2','Fitting data2');
title('Fitting Result');
figure(2)
plot(x,data1,'-ko','MarkerFace','g'),hold on;
plot(x,PR1(1)*(tansig(-PR1(2)*(x-PR1(3))/PR1(4))+PR1(5)),'-ks','MarkerFace','r'),hold on;
set(gca,'Ygrid','on'); 
legend('Testing data','Fitting data');
figure(3)
plot(x,data2,'-ko','MarkerFace','g'),hold on;
plot(x,PR2(1)*(tansig(-PR2(2)*(x-PR2(3))/PR2(4))+PR2(5)),'-ks','MarkerFace','r'),hold on;
set(gca,'Ygrid','on'); 
%set(gca,'xticklabel',''),set(gca,'yticklabel',''); %关闭X/Y坐标显示
legend('Testing data','Fitting data');
figure(4)%Polynomial fitting
Polynomial;


function f=fun(X,xdata)%自定义S曲线非线性函数
f=X(1)*(tansig(-X(2)*(xdata-X(3))/X(4))+X(5));
function Polynomial
x=1:10:81;
y1=[-20 -90 -100 -100 -100 -100 -100 -100 -100];
y2=[-20 -78 -94 -99 -100 -100 -100 -100 -100];
g=[-100 -100 -100 -100 -100 -100 -100 -100 -100];
p1=polyfit(x,y1,8);  
p2=polyfit(x,y2,8); 
xi=1:0.2:81;
yi1=polyval(p1,xi);  
yi2=polyval(p2,xi);
plot(x,y1,'-ko','linewidth',1.5,'MarkerFace','b'),grid on,hold on;
plot(x,y2,'-sk','linewidth',1.5,'MarkerFace','y'),grid on,hold on;
plot(x,g,'g:','linewidth',1.5),grid on,hold on;
plot(xi,yi1,'r-','linewidth',1.5),grid on,hold on;
plot(xi,yi2,'--','color',[153 0 153]/255,'linewidth',1.5),grid on,hold on;
legend('data1','data2','目标','跟踪拟合1','跟踪拟合2');
xlabel('Time(s)'),ylabel('Deep(m)');
axis([0 80 -110 -10]); 
set(gca,'Ygrid','on'); 
title('Fitting Result');

你可能感兴趣的:(数据拟合,Matlab代码)