Emily
Emily

Reputation: 29

How to find the average of a subset of cells in matlab?

I have the results of an experiment in which participants give a rating from 0-9 (dependent variable) in 5 different conditions (independent variable), in a random order. I get numeric arrays similar to this

ratings = [ 5 7 2 4 8 7 6 3 5 6]   
level   = [ 1 5 3 3 2 4 5 4 1 2]

I would like to find the average ratings for each level of my experiment, so i can eventually plot as a scatter plot. Could anyone point me in the direction of how to do this?

Upvotes: 1

Views: 52

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

I would go for the accumarray solution. But just for variety, this also works:

result = nonzeros(sparse(level,1,ratings))./nonzeros(sparse(level,1,1));

Upvotes: 1

Suever
Suever

Reputation: 65430

If you want to compute the mean rating for each level, you can use accumarray to do this. What accumarray will do is group ratings by their corresponding value in level. Then it will apply the function specified as the fourth input to each of these groups. In your case, we use @mean to simply compute the mean of all ratings which share the same level value.

accumarray(level(:), ratings(:), [], @mean);

%        5
%        7
%        3
%        5
%      6.5

Upvotes: 1

Related Questions