随笔 - MATLAB 练习:直方图,归一化和概率分布拟合

histogramfitdist 用法一例

题目

以 2011 年中国 CPI 的三个增长率 (环比增长率,同比增长率,累计增长率) 为例

  1. 根据数据做出三个增长率的直方图与折线图
  2. 用某一分布拟合归一化后的直方图并给出误差

数据如下

data.mview raw
1
2
3
4
5
6
% Round-ratio growth rate
RGR = [1.0, 1.3, -0.2, 0.1, 0.1, 0.3, 0.5, 0.3, 0.5, 0.1, -0.2, 0.3];
% Year-on-year growth rate
YGR = [4.9, 4.9, 5.4, 5.3, 5.5, 6.4, 6.5, 6.2, 6.1, 5.5, 4.2, 4.1];
% Accumulated growth rate
AGR = [4.9, 4.9, 5.0, 5.1, 5.2, 5.4, 5.5, 5.6, 5.7, 5.6, 5.5, 5.4];

主要命令用法简介

histogram

用途

画直方图

本例中涉及的用法

  • histogram(data): 对给定数据画直方图
  • histogram(data, nbins): 指定 bin 数目,对给定数据画直方图
  • histogram(data, [], name, value): 更改指定属性
  • Normalization: 归一化属性,默认为 count
    • count: 即不做处理
    • pdf: 概率密度函数的估计值,使用此属性能使直方图总面积 \(\leqslant 1\) (\(<1\) 当且仅当数据中出现 NaN 等)
  • h = histogram(data): h 为直方图对象,用于获取和修改直方图数据
  • h.Values: 即每个 bin 对应的值

fitdist

用途

对给定数据和概率分布类型进行拟合

本例中涉及的用法

  • pd = fitdist(x, distname): 对给定数据和概率分布类型进行拟合

实际上本题可以使用 histfit 命令同时绘制直方图和拟合曲线,但因为笔者在调取其返回的句柄时出现了问题,故未使用

代码与结果

问题 1

Show code 1

q1.mview raw
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
% Plot histogram and line chart with given data

% @Author: Tifa
% @LastEditTime: 2021-04-12 19:24:47

% Data
% Round-ratio growth rate
RGR = [1.0, 1.3, -0.2, 0.1, 0.1, 0.3, 0.5, 0.3, 0.5, 0.1, -0.2, 0.3];
% Year-on-year growth rate
YGR = [4.9, 4.9, 5.4, 5.3, 5.5, 6.4, 6.5, 6.2, 6.1, 5.5, 4.2, 4.1];
% Accumulated growth rate
AGR = [4.9, 4.9, 5.0, 5.1, 5.2, 5.4, 5.5, 5.6, 5.7, 5.6, 5.5, 5.4];

R = [RGR; YGR; AGR];
strR = ['RGR'; 'YGR'; 'AGR'];
nbins = 6;

for i = 1:3
% Plot histogram
subplot(2, 3, i)
histogram(R(i, :), nbins)
title(sprintf('histogram of %s', strR(i, :)))
xlabel('Rate/%')
ylabel('Frequency')

% Plot line chart
subplot(2, 3, 3 + i)
plot(R(i, :))
title(sprintf('line chart of %s', strR(i, :)))
xlabel('Month')
ylabel('Rate/%')
grid on
end
RGRYGRAGR

问题 2

Show code 2

q1.mview raw
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
% Plot histogram and line chart with given data

% @Author: Tifa
% @LastEditTime: 2021-04-12 19:24:47

% Data
% Round-ratio growth rate
RGR = [1.0, 1.3, -0.2, 0.1, 0.1, 0.3, 0.5, 0.3, 0.5, 0.1, -0.2, 0.3];
% Year-on-year growth rate
YGR = [4.9, 4.9, 5.4, 5.3, 5.5, 6.4, 6.5, 6.2, 6.1, 5.5, 4.2, 4.1];
% Accumulated growth rate
AGR = [4.9, 4.9, 5.0, 5.1, 5.2, 5.4, 5.5, 5.6, 5.7, 5.6, 5.5, 5.4];

R = [RGR; YGR; AGR];
strR = ['RGR'; 'YGR'; 'AGR'];
nbins = 6;

for i = 1:3
% Plot histogram
subplot(2, 3, i)
histogram(R(i, :), nbins)
title(sprintf('histogram of %s', strR(i, :)))
xlabel('Rate/%')
ylabel('Frequency')

% Plot line chart
subplot(2, 3, 3 + i)
plot(R(i, :))
title(sprintf('line chart of %s', strR(i, :)))
xlabel('Month')
ylabel('Rate/%')
grid on
end
RGRYGRAGR

主要参考资料