grouped average in arrays
27 次查看(过去 30 天)
显示 更早的评论
I have two arrays:
A=[1,2,3,1,3,4,2,5,6,7,3,4]
B=[a,a,a,b,b,b,c,c,d,d,d,b]
where person 'a' has scores 1,2,3; person 'b' has scores 1,3,4,4. I want to get an average of the scores per person. So the output aray will be: avgScores = [2,3,3.5,5]. avgScores is in the same order as uB.
My idea is to get uB = unique(B) and then find idx of each element in uB from B, then use these idx to get the scores from A and compute the average.
uB = unique(B)
for i=1:size(uB,1)
idx=strfind(B,uB(i)) %returns a full array with ones in place of match
scores = A(idx) %does not work
avgScores(i) = average(scores)
end
The problem is that I can not get the idx from B, it returns an array the size of B, with empty arrays in no matches, and 1s in matches. So the next step does not work.
Any help is appreciated.
0 个评论
回答(3 个)
madhan ravi
2019-1-24
编辑:madhan ravi
2019-1-24
Requires 2018a or later:
T=table;
T.Group=B.';
T.Values=A.';
G=findgroups(T.Group);
groupsummary(T,'Group','mean')
Note: The last value should be 5.3333 not 5.
0 个评论
madhan ravi
2019-1-24
Requires 2015b or later:
T=table;
T.Group=B.';
T.Values=A.';
G=findgroups(T.Group);
avgscores=splitapply(@mean,T.Values,G)
0 个评论
Andrei Bobrov
2019-1-24
Old MATLAB
T = table(A(:),repelem(string(['a':'d','b']'),[3,3,2,3,1]),'v',{'A','B'});
outT = varfun(@mean,T,'G',2);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!