使用百分比函数与accumarray

时间:2015-06-04 05:40:46

标签: arrays matlab percentage accumarray

我有两个数组:

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,...];

我曾经和#34; accumarray"但是我使用了"意思是"或"总和"这样的功能:

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

我只是想知道是否有一种方法可以使用它,但是" prctile"函数或任何其他函数,它给出了特定元素的百分比,例如" 1"在这种情况下。

非常感谢。

3 个答案:

答案 0 :(得分:5)

这可能是一种方法:

%// 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

答案 1 :(得分:4)

这是另一种不使用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中找到那些唯一的元素。完成此操作后,我们首先通过histc计算PCORorder中每个唯一值所属的元素数量,并使用这些精确列表进行计数。如果您正在使用更新版本的MATLAB,请使用histcounts代替...相同的语法。在PCORorder中找到每个值的元素总数后,我们只需计算与PCORorder AprefCOR == 1对应的元素数量,然后计算百分比,您只需将每个条目分开在此列表中,包含上一个列表中的元素总数。

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

答案 2 :(得分:3)

您的方法有效,您只需要定义anonymous function要使用的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);