grouped average in arrays

28 Ansichten (letzte 30 Tage)
Tooba Sheikh
Tooba Sheikh am 24 Jan. 2019
Beantwortet: Andrei Bobrov am 24 Jan. 2019
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.

Antworten (3)

madhan ravi
madhan ravi am 24 Jan. 2019
Bearbeitet: madhan ravi am 24 Jan. 2019
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 am 24 Jan. 2019
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 am 24 Jan. 2019
Old MATLAB
T = table(A(:),repelem(string(['a':'d','b']'),[3,3,2,3,1]),'v',{'A','B'});
outT = varfun(@mean,T,'G',2);

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by