问题描述
假设我有矩阵A.第一列是组".然后,我想计算每组第二列的平均值.所以我想创建B.
Suppose I have matrix A. 1st column is "group". Then I want to calculate the average of 2nd column for each group. So I want to create B.
A=
1 2
1 3
2 4
2 2
B=
1 2.5
2 3
到目前为止,我所做的最好的事情是构造一个long for和if循环,并使用average函数到达B.
The best thing I did until now is to construct a long for and if loop and use average function to get to B.
但是我想会有更简单的方法.有吗?
But I guess there will be more simple method. Is there?
推荐答案
我没有使用 accumarray
之前,因此由于@Dan的评论,我决定尝试一下.
I hadn't used accumarray
before, so due to the comment by @Dan I decided to give it a try.
起初,我尝试过一个简单的版本,并使用histc
对出现的次数进行计数以获得所需的平均值...(请注意,accumarray将对输出进行排序,使其与unique
的顺序相同,因此均值将被正确计算)
At first I tried a naive version and used histc
to count occurrences to get the desired mean values... (Note that accumarray will sort the output the same order as unique
, so mean will be calculated correctly)
%// Naive version
ua = unique(A(:,1)); %// use as histc bins (or sorted "group" values)
result = accumarray(A(:,1), A(:,2)) ./ histc(A(:,1), uA);
在这里,accumarray
通过对A(:,2)
中与A(:,1)
中相同下标相对应的所有条目求和.
Here, accumarray
operates by summing over all entries in A(:,2)
corresponding to identical subscripts in A(:,1)
.
但是后来我意识到,通过将可选的fun
参数传递给accumarray
,将"summing"更改为"mean",您可以将其作为单行代码进行:
But then I realised that by passing the optional fun
argument to accumarray
changing "summing" to "mean", you can do this as a one-liner:
%// one-liner
result = accumarray(A(:,1), A(:,2), [], @mean);
这篇关于第二列子组的平均值,按第一列分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!