interpolation and fitting

现实世界中的数据都是离散的,那么我们怎么将离散的点,尽量的使他们分布在函数上呢?于是就要运用插值与拟合的相关知识。
插值和拟合的理论有点懵,先学一下怎么画图吧。

example1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
x = [0.5 1 1.5 2.5 3 3.5 4.5 5];
y = [2 2.1 2.3 2.6 2.9 3.2 4 4.5];
y_lookup = interp1(x, y, 0.7);
fprintf('x = 0.7, y = %.3f\n', y_lookup);
x_new = 0.5: 0.5: 5;
y_new = interp1(x, y, x_new);
figure(2);%新创建一个图,不覆盖原来的图片
plot(x, y, 'o', x_new, y_new, 'x');
x_resample = min(x): 0.01: max(x);
y_resample = interp1(x, y, x_resample);
figure(3);
plot(x, y, 'o', x_resample, y_resample, '-', 'LineWidth', 2);
p1 = polyfit(x, y, 1);%1是多项式的最高的次数,p1是各项的系数,最后是常数项
y_fit1 = polyval(p1, x);
figure(4);
plot(x, y, 'o', x, y_fit1, '--', 'LineWidth', 2);
p2 = polyfit(x, y, 2);
y_fit2 = polyval(p2, x);
figure(5);
plot(x, y, 'o', x, y_fit2, '--', 'LineWidth', 2);

example2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
% the first m file.
% this function can be completed by the polyfit function.
function y = f(constant, x)
y = constant(1)*x+constant(2);
end
% the second m file.
x = rand(1, 100).*10;%生成1*100的(0,1)之间的随机数
noise = randn(1, 100);%生成正态分布的随机数
y = 2*x + 5 + noise;
figure;
plot(x, y, 'b*');
grid on;
% y = mx + c;
constant = lsqcurvefit(@f, [0; 0], x, y);
m = constant(1);
c = constant(2);
xfit = 0:0.1:10;
yfit = f(constant, xfit);
figure;
plot(x, y, 'b*');
hold on;
plot(xfit, yfit, 'LineWidth', 2);
grid on;
or the following function
x = rand(1, 100).*10;%生成1*100的(0,1)之间的随机数
noise = randn(1, 100);%生成正态分布的随机数
y = 2*x + 5 + noise;
figure;
plot(x, y, 'b*');
p1 = polyfit(x, y, 1);
y1 = polyval(p1, x);
figure;
plot(x, y, 'b*', x, y1, 'r--');
grid on;

example3: 绘制曲线

1
2
3
4
5
6
7
8
9
10
11
12
13
14
x = 0: pi/2: 2*pi;
y = sin(x);
xq = 0: pi/16: 2*pi;//插值
figure;
yq1 = interp1(x, y, xq);
plot(x, y, 'o', xq, yq1, ':.');
figure
yq2 = interp1(x,y,xq,'spline');
plot(x,y,'o',xq,yq2,':.');
xlim([0 2*pi]);//设置x变量的变化的区间的范围
title('Spline Interpolation');

spline()的中文名为样条插值函数,三次样条插值,然而还是不懂原理。

文章目录
  1. 1. example1
  2. 2. example2
  3. 3. example3: 绘制曲线
{{ live2d() }}