average each block of class in a matrix

조회 수: 2 (최근 30일)
alessio tugnolo
alessio tugnolo 2020년 3월 16일
편집: Guillaume 2020년 3월 16일
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!

채택된 답변

Guillaume
Guillaume 2020년 3월 16일
편집: Guillaume 2020년 3월 16일
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

추가 답변 (1개)

Sriram Tadavarty
Sriram Tadavarty 2020년 3월 16일
Hi Alessio,
The mean function will help in this case. Here is the documentation page of mean function having different exampleshttps://www.mathworks.com/help/matlab/ref/mean.html
% Consider a random matrix
a = randn(1000,10000); % Implies 1000 rows and each row containing 10000 columns
% Calculate the mean of each column
meCol = mean(a);
% Calculate the mean of each row
meRow = mean(a,2); % This is your intended case
Hope this helps.
Regards,
Sriram
  댓글 수: 2
alessio tugnolo
alessio tugnolo 2020년 3월 16일
Thank you so much Sriram!
I have a situation like that:
I would obtain an average row of each time. Consider that each class haven't the same number of objects.
Thank you!
Sriram Tadavarty
Sriram Tadavarty 2020년 3월 16일
Hi Alessio,
In this case, you can run a fop loop on number of rows and take mean for each row.
% Rows variable is a cell array with different number of elements in it. For example
Rows = {[1 4 5],[1 9 10 100]};
for i = 1:numel(Rows)
avg(i) = mean(Rows{i});
end
% avg returns [3.3333 30.0000] each element corresponding to each row
Hope this helps
Sriram

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Elementary Math에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by