如何计算 Matlab 中的百分比份额

How to calculate percentile shares in Matlab

我有一些数据包含有关名为“财富”的变量的信息。

我想计算分布顶部、中间和底部的份额。这就是富人、中等人和穷人拥有多少财富。

模拟示例是从伽玛分布中抽取 10000 个随机变量,因此假设分布是这样的:

wealth = gamrnd(shape,scale,n,1);

那么我如何计算这个变量有多少去说前 10%、后 90% 等...

有人可以帮助我如何在 Matlab 中做到这一点吗?

您可以使用以下基于数据排序的功能:

function [ topVals, bottomVals ] = calcPercentile( x, percentile )
    sortedX = sort(x,'descend');
    m = int16(percentile*length(x));
    topVals = sortedX(1:m);
    bottomVals = sortedX(m+1:end);
end

用法示例:

%getting top 10% and bottom 90%
[ topVals, bottomVals ] = calcPercentile(x,0.1);
%getting top 40% and bottom 60%
[ topVals, bottomVals ] = calcPercentile(x,0.4);

结果:

topVals = 10
bottomVals =   9     8     7     6     5     4     3     2     1

topVals =  10     9     8     7
bottomVals =     6     5     4     3     2     1

要计算百分位数,您可以使用 matlab 的函数 prctile。调用函数的方法之一是

prctile(X,p)

其中 X 是您的向量,p 是 [0-100] 范围内的百分比。请注意,这就是您所说的 "bottom percentage"

在您的情况下,您可以按如下方式获得最低的 n%:

ninetyPercentBottom = prctile(X,n)
ninetyPercentBottomShare = sum(X(X<ninetyPercentBottom))/sum(X)

如果您想要 "top percentage",请注意 "bottom percentage" n% 与 "top percentage" 100-n% 相同,因此您可以使用该想法来获得份额前 n%

topPercentile = 10
tenPercentTop = prctile(X,100-topPercentile)
tenPercentTopShare = sum(X(X>tenPercentTop))/sum(X)