数据拟合—MATLAB

1,多项式拟合:

f=polyfit(x,y,n),对数据x,y进行n次项拟合,x,y要有相同的维度。

polyval(f,xi)%xi是插值变密集后的一组数组,一般绘图用,计算出多项式的值

例子:

x = linspace(0,4*pi,10);
y = sin(x);

Use polyfit to fit a 7th-degree polynomial to the points.

p = polyfit(x,y,7);

Evaluate the polynomial on a finer grid and plot the results.

x1 = linspace(0,4*pi);
y1 = polyval(p,x1);
figure
plot(x,y,'o')
hold on
plot(x1,y1)
hold off

最后的绘图效果:


2.指定函数拟合

(1):fit()和fittype()%具体见help文件,内容较多

g = fittype( @(a, b, c, d, x, y) a*x.^2+b*x+c*exp(...
 -(y-d).^2 ), 'independent', {
  
  'x', 'y'},...
     'dependent', 'z' );
 
 
myfittype = fittype('a*x.^2+b*x+c*exp(-(y-d).^2)',...
    'dependent',{
  
  'x,y'},'independent',{
  
  'x'},...
    'coefficients',{
  
  'a','b'})%引号是转行地作用
注意两种定义函数的区别。其中‘independent’后面写的是定义谁是变量,‘coefficient’后面接的是谁是未知系数。

(2):lsqcurvefit拟合

x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub),fun为函数,若是函数句柄@定义,则直接填函数fun,若是.m文件定义,则打文件名的引号。x0是定义的搜寻初值,xdata,ydata,是要拟合的数据,lb,ub是限制解x的范围,最后得到的答案x只会在lb,ub之间,即lb<=x<=ub.若不限定,则不填,或者写[],[].

annotation:

fun的写法。例如对f=a*x^2+sin(b*x)-exp(-c*x);拟合,因为拟合就是确定函数系数a,b,c的过程,则定义时要用统一的变量来表示系数,f=@(a,x)a(1)*x^2+sin(a(2)*x)-exp(-a(3)*x).用a(1),a(2),a(3)来统一表示系数,在用文件定义时同理。

猜你喜欢

转载自blog.csdn.net/weixin_40244676/article/details/80141585