使用百分比函数与数组



我有两个数组:

OTPCORorder = [61,62,62,62,62,62,62,62,62,62,62,62,65,65,...]
AprefCOR = [1,3,1,1,1,1,1,1,1,1,2,3,3,2,...]

对于OTPCORorder中的每个元素,在AprefCOR中都有一个相应的元素。我想知道每组唯一OTPCORorder中数字1的百分比,如下所示:

OTPCORorder1 = [61,62,65,...]
AprefCOR1 = [1,0.72,0,...]

我已经有这个了:

[OTPCORorder1,~,idx] = unique(OTPCORorder,'stable');
ANS = OTPCORorder1 = [61,62,65,...];

和我过去使用的是"accumarray",但我使用的是"mean"或"sum"函数,如:

AprefCOR1 = accumarray(idx,AprefCOR,[],@mean).';

我只是想知道是否存在一种方法来使用这个,但与"实用"函数或任何其他函数,给我一个特定元素的百分比,例如"1"在这种情况下。

这可能是一种方法:

%// make all those non-zero values to zero
AprefCORmask = AprefCOR == 1;
%// you have done this
[OTPCORorder1,~,idx] = unique(OTPCORorder,'stable');
%// Find number of each unique values
counts = accumarray(idx,1);
%// Find number of ones for each unique value
sumVal = accumarray(idx,AprefCORmask);
%// find percentage of ones to get the results
perc = sumVal./counts

结果:

输入:

OTPCORorder = [61,62,62,62,62,62,62,62,62,62,62,62,65,65];
AprefCOR = [1,3,1,1,1,1,1,1,1,1,2,3,3,2];
输出:

perc =
1.0000
0.7273
     0

这里是不使用accumarray的另一种方法。我觉得这样更容易读懂:

>> list = unique(PCORorder);
>> counts_master = histc(PCORorder, list);
>> counts = histc(PCORorder(AprefCOR == 1), list);
>> perc = counts ./ counts_master
perc =
    1.0000    0.7273         0

以上代码的工作原理是,我们首先找到PCORorder中唯一的元素。一旦我们这样做了,我们首先计算有多少元素属于PCORorderhistc中的每个唯一值,使用箱子来计算这个确切的列表。如果您使用的是较新版本的MATLAB,请使用histcounts代替…相同的语法。一旦我们找到PCORorder中每个值的元素总数,我们只需计算PCORorderAprefCOR == 1对应的元素数量,然后计算百分比,只需将此列表中的每个条目除以前一个列表中的元素总数。

它将提供与accumarray相同的结果,但开销更少。

您的方法有效,您只需要定义一个适当的匿名函数供accumarray使用。设value = 1为要计算其百分比的值。

[~, ~, u] = unique(OTPCORorder); %// labels for unique values in OTPCORorder
result = accumarray(u(:), AprefCOR(:), [], @(x) mean(x==value)).';

作为一种替代方法,您可以使用sparse,如下所示。生成一个两行矩阵,使每一列对应于OTPCORorder中的一个可能值。第一行计算OTPCORorder中的每个值与AprefCOR中的期望值对应的次数;第二行是它没有出现的次数

[~, ~, u] = unique(OTPCORorder);
s = full(sparse((AprefCOR==value)+1, u, 1));
result = s(2,:)./sum(s,1);

最新更新