MATLAB: Average each block of class in a matrix

average matrixclass average

Hi, I have a large matrix where the rows are labelled according to different classes. I would like to obtain an average row of each class. How can I do it?
Thank you!

Best Answer

It's unclear how your input data is actually stored in matlab so please clarify if the below doesn't apply.
I'm assuming that you have a two column matrix with one column storing the the class and the other the column storing the values you want to average by class. In this case, this is trivially achieved with groupsummary:
classcolumn = 1; %change as appropriate
valuecolumn = 2; %can be more than one column. Each column will be average by class
classmean = groupsummary(yourmatrix, classcolumn, 'mean', valuecolumn);
Other simple ways this can be achieved: splitapply or accumarray:
classcolumn = 1;
valuecolumn = 2;
group = findgroups(yourmatrix(:, classcolumn));
classmean = splitapply(@mean, yourmatrix(:, valuecolumn), group);
%or
classmean = accumarray(group, yourmatrix(:, valuecolumn), [], @mean); %this one can only work on one column though