grouped average in arrays
조회 수: 28 (최근 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!