grouped average in arrays

16 ビュー (過去 30 日間)
Tooba Sheikh
Tooba Sheikh 2019 年 1 月 24 日
回答済み: Andrei Bobrov 2019 年 1 月 24 日
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.

回答 (3 件)

madhan ravi
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.

madhan ravi
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)

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by