find the mean for each category and summarize it

조회 수: 31 (최근 30일)
Mohammad Aljarrah
Mohammad Aljarrah 2020년 3월 4일
댓글: Mohammad Aljarrah 2020년 3월 4일
Hello,
i have a table which consists of the following data
Category value1 value2
1 20 33
3 23 43
2 50 32
4 13 32
4 30 15
3 33 23
1 60 12
2 24 43
i want to find the modulus mean value for each unique category and summarize them, e.g.
Category value1 value2
1 23.54 15.33
2 35.44 42.55
3 29.33 33.32
4 44.34 23.44
can anyone help me with this?
  댓글 수: 3
the cyclist
the cyclist 2020년 3월 4일
Sorry I deleted my question that you answered here! I decided to just illustrate solutions for both a numeric array and a table.
Star Strider
Star Strider 2020년 3월 4일
@Mohammad Aljarrah — How do you calculate those results?
The mean of category 1 for example are 40 and 22.5 for ‘value1’ and ‘value2’ respectively. How do you get 23.54 and 15.33?

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

채택된 답변

the cyclist
the cyclist 2020년 3월 4일
편집: the cyclist 2020년 3월 4일
For a numeric array, you can use the accumarray function to do this. That function is a bit tricky to learn the power of, and is also not really set up for operating on a matrix of data. However, Sean de Wolski provided a nice solution here, which I borrow below.
For a table, it is simpler. You can use grouping variables in the varfun function.
I illustrate both below.
M = [1 20 33
3 23 43
2 50 32
4 13 32
4 30 15
3 33 23
1 60 12
2 24 43];
% On the original matrix
[~,~,c] = unique(M(:,1));
data = M(:,[2 3]);
sz = size(data);
meanByCategoryForMatrix = accumarray([repmat(c,sz(2),1), repelem((1:sz(2))',sz(1),1)],data(:),[],@mean)
% Or put them in a table first
Category = M(:,1);
value1 = M(:,2);
value2 = M(:,3);
tbl = table(Category,value1,value2);
meanByCategoryForTable = varfun(@mean,tbl,'GroupingVariables','Category','InputVariables',{'value1','value2'})

추가 답변 (1개)

Robert U
Robert U 2020년 3월 4일
Hi Mohammad Aljarrah,
the function that calculates the desired values can be exchanged according to your needs. I used the "mean" (within "arrayfun") to illustrate the solution to your described problem:
testData = [1, 20, 33
3, 23, 43
2, 50, 32
4, 13, 32
4, 30, 15
3, 33, 23
1, 60, 12
2, 24, 43 ];
catTestData = unique(testData(:,1));
outMean = [catTestData cell2mat(arrayfun(@(dIn) mean(testData(testData(:,1) == dIn,2:3),1),catTestData,'UniformOutput',false))];
Kind regards,
Robert
  댓글 수: 1
Mohammad Aljarrah
Mohammad Aljarrah 2020년 3월 4일
thank you very much Robert, that worked perfectly

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

카테고리

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

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by