Average of subgroup of 2nd column, grouped by 1st column

后端 未结 1 1264
情歌与酒
情歌与酒 2020-12-22 07:36

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         


        
相关标签:
1条回答
  • 2020-12-22 08:19

    I hadn't used accumarray before, so due to the comment by @Dan I decided to give it a try.

    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);
    

    Here, accumarray operates by summing over all entries in A(:,2) corresponding to identical subscripts in A(:,1).

    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);
    
    0 讨论(0)
提交回复
热议问题