数据拟合
clc,clear;
x=[0.5,1.0,1.5,2.0,2.5,3.0];
y=[1.75,2.45,3.81,4.80,7.00,8.60];
p=polyfit(x,y,2);
x1=0.5:0.05:3.0;
y1=polyval(p,x1);
plot(x,y,'*r',x1,y1,'-b');
result
p=polyfit(x,y,n):最小二乘法计算拟合多项式系数。x,y为拟合数据向量,要求维度相同,n为拟合多项式次数。返回p向量保存多项式系数,由最高次向最低次排列。
y=polyval(p,x):计算多项式的函数值。返回在x处多项式的值,p为多项式系数,元素按多项式降幂排序。
clc,clear;
close all;
%将参数a,b合写为向量c
fun=inline('c(1)*exp(c(2)*x)','c','x');
x=[0.1,0.2,0.15,0,-0.2,0.3];
y=[0.95,0.84,0.86,1.06,1.50,0.72];
c=lsqcurvefit(fun,[0,0],x,y)
norm(feval(fun,c,x)-y)^2%计算残差的平方和
result
Local minimum found.
Optimization completed because the size of the gradient is less than
the value of the optimality tolerance.
c =
1.0997 -1.4923
ans =
0.0031
2019高教社杯A题拟合
clc,clear;
close all;
x=xlsread('needle_valve_motion_curve.xls','A2:A46');
y=xlsread('needle_valve_motion_curve.xls','B2:B46');
p=polyfit(x,y,3);
x1=0:0.01:0.44;
y1=polyval(p,x1);
plot(x,y,'*r',x1,y1,'-b');
figure;
x2=xlsread('needle_valve_motion_curve.xls','D2:D46');
y2=xlsread('needle_valve_motion_curve.xls','E2:E46');
p2=polyfit(x,y,3);
x21=2.01:0.01:2.45;
y21=polyval(p2,x21);
plot(x,y,'*r',x1,y1,'-b');
result