如何在Matlab中计算财富分布的百分位数份额?
嘿,这个需求在财富分布分析里太常见了!我来给你一步步拆解怎么用Matlab实现,刚好你用了伽马分布的示例,咱们就顺着这个来:
步骤1:生成财富数据
先按你的示例生成10000个伽马分布的财富数据,这里我给shape和scale赋具体值,方便你直接运行:
shape = 2; scale = 5; n = 10000; wealth = gamrnd(shape, scale, n, 1);
步骤2:对财富数据排序
要划分阶层的话,先把财富从小到大排序是最直观的操作:
sorted_wealth = sort(wealth, 'ascend');
步骤3:计算各阶层的边界索引
假设你要算**顶层10%、中层80%、底层10%**的财富占比,先算出各部分对应的样本索引:
bottom_pct = 0.1; % 底层比例 top_pct = 0.1; % 顶层比例 bottom_idx = round(n * bottom_pct); % 底层群体的最后一个索引 top_start_idx = n - round(n * top_pct) + 1; % 顶层群体的第一个索引
注意:这里用round是为了把人数取整,如果你的样本量不是整百整千,也可以根据需求用floor(向下取整)或ceil(向上取整),结果差异很小
步骤4:计算各阶层的财富占比
先算总财富,再分别计算各阶层的财富总和,最后除以总财富得到占比:
total_wealth = sum(wealth); % 计算各阶层财富总和 bottom_wealth = sum(sorted_wealth(1:bottom_idx)); middle_wealth = sum(sorted_wealth(bottom_idx+1:top_start_idx-1)); top_wealth = sum(sorted_wealth(top_start_idx:end)); % 转成百分比形式 bottom_share = bottom_wealth / total_wealth * 100; middle_share = middle_wealth / total_wealth * 100; top_share = top_wealth / total_wealth * 100;
步骤5:输出结果
用fprintf把结果打印出来,更直观:
fprintf('底层%.0f%%群体财富占比: %.2f%%\n', bottom_pct*100, bottom_share); fprintf('中层%.0f%%群体财富占比: %.2f%%\n', (1-bottom_pct-top_pct)*100, middle_share); fprintf('顶层%.0f%%群体财富占比: %.2f%%\n', top_pct*100, top_share);
额外技巧:用分位数函数快速划分
如果你不想手动算索引,也可以用Matlab的quantile函数直接找到分位数边界,再筛选对应群体:
q10 = quantile(wealth, 0.1); % 10%分位数 q90 = quantile(wealth, 0.9); % 90%分位数 bottom_wealth = sum(wealth(wealth < q10)); middle_wealth = sum(wealth(wealth >= q10 & wealth <= q90)); top_wealth = sum(wealth(wealth > q90));
注意:quantile函数默认的分位数计算方法是type=7,和排序取索引的结果可能略有差异。如果要完全一致,可以把type参数设为6:quantile(wealth, 0.1, 'Type', 6)
如果要调整比例(比如顶层5%、底层20%),只需要修改bottom_pct和top_pct的值,或者分位数的数值就行,非常灵活。
内容的提问来源于stack exchange,提问作者msh855
相关产品推荐
相关产品推荐

