grouped average in arrays

조회 수: 28 (최근 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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by