# MATLAB学习笔记（十一）

## 在本章中将要学习以下内容：

1. 用线性模拟或三次样条模型求数据的插值
2. 将一维数据点建模为一个多项式
3. 使用基本拟合工具
4. 使用曲线拟合工具
5. 进行数值积分
6. 进行数值微分
7. 求解微分方程的数值解

## 一.插值

1.线性插值

>> x = 0:5
x =
0     1     2     3     4     5
>> y = [15,10,9,6,2,0];
>> interp1(x,y,3.5)
ans =
4 

interp1的第三个输入参数可以是矢量，可以进行多点插值运算：

>> new_x = 1:0.2:5;
>> interp1(x,y,new_x)
ans =
Columns 1 through 11
10.0000    9.8000    9.6000    9.4000    9.2000    9.0000    8.4000    7.8000    7.2000    6.6000    6.0000
Columns 12 through 21
5.2000    4.4000    3.6000    2.8000    2.0000    1.6000    1.2000    0.8000    0.4000         0

>> new_y = ans;
>> plot(x,y,new_x,new_y,'o') 

>> interp1(x,y,3.5,'linear')
ans =
4 

2.三次样条插值

>> interp1(x,y,3.5,'spline')
ans =
3.9417 

>> new_x = 0:0.2:5;
>> new_y_spline = interp1(x,y,new_x,'spline')
new_y_spline =
Columns 1 through 11
15.0000   13.3088   12.0251   11.0869   10.4325   10.0000    9.7275    9.5531    9.4149    9.2512    9.0000
Columns 12 through 22
8.6133    8.0987    7.4773    6.7707    6.0000    5.1872    4.3563    3.5317    2.7381    2.0000    1.3419
Columns 23 through 26
0.7883    0.3637    0.0928         0
>> plot(x,y,new_x,new_y_spline,'-o')

‘linear’ 线性插值，函数的默认功能
‘nearest’ 最邻近点内插
‘spline’ 三次样条插值
‘pchip’ 形状保持分段三次插值
‘cubic’ 形状保持分段三次插值

3.多维插值

>> y = 2:2:6;
>> x = 1:4;
>> z = [7,15,22,30;54,109,164,218;403,807,1210,1614];
>> interp2(x,y,z,1.5,3)
ans =
46.2500

MATLAB提供三维插值函数interp3和n维插值函数interpn.

## 二.曲线拟合

1.线性回归

>> x = [0:5];
>> y = [15,10,9,6,2,0];
>> polyfit(x,y,1)
ans =
-2.9143   14.2857 

>> best_y = -2.9143 * x + 14.2857
best_y =
14.2857   11.3714    8.4571    5.5428    2.6285   -0.2858
>> new_sum = sum((y - best_y) .^ 2)
new_sum =
3.3714 

>> plot(x,y,'o',x,best_y)

2.多项式回归

>> x
x =
0     1     2     3     4     5
>> y
y =
15    10     9     6     2     0
>> polyfit(x,y,2)
ans =
0.0536   -3.1821   14.4643
>> polyfit(x,y,3)
ans =
-0.0648    0.5397   -4.0701   14.6587 

>> smooth_x = 0:0.2:5;
>> smooth_y2 = 0.0536 * smooth_x.^2 - 3.182 * smooth_x + 14.4643;
>> subplot(1,2,1)
>> plot(x,y,'o',smooth_x,smooth_y2)
>> axis([0,6,-5,15]);
>>
>> smooth_y3 = -0.0648 * smooth_x.^3 + 0.5398 * smooth_x.^2 - 4.0701 * smooth_x + 14.6587;
>> subplot(1,2,2)
>> plot(x,y,'o',smooth_x,smooth_y3)

3.函数polyval

>> coef = polyfit(x,y,1)
coef =
-2.9143   14.2857
>> y_first_order_fit = polyval(coef,x)
y_first_order_fit =
14.2857   11.3714    8.4571    5.5429    2.6286   -0.2857

>> y_first_order_fit = polyval(polyfit(x,y,1),x)
y_first_order_fit =
14.2857   11.3714    8.4571    5.5429    2.6286   -0.2857 

>> y4 = polyval(polyfit(x,y,4),smooth_x);
>> y5 = polyval(polyfit(x,y,5),smooth_x);
>> subplot(1,2,1)
>> plot(x,y,'o',smooth_x,y4)
>> axis([0,6,-5,15])
>> subplot(1,2,2)
>> plot(x,y,'o',smooth_x,y5)
>> axis([0,6,-5,15])

## 三.使用交互式拟合工具

1.基本拟合工具

>> x  = 0:5;
>> y = [0,20,60,68,77,110];
>> y2 = 20 * x;
>> plot(x,y,'o')
>> axis([-1,7,-20,120])

2.曲线拟合工具箱

• 本文已收录于以下专栏：

举报原因： 您举报文章：MATLAB学习笔记（十一） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)