4 views (last 30 days)

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?

the cyclist
on 4 Mar 2020

Edited: the cyclist
on 4 Mar 2020

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.

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'})

Robert U
on 4 Mar 2020

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

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/508970-find-the-mean-for-each-category-and-summarize-it#comment_805278

⋮## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/508970-find-the-mean-for-each-category-and-summarize-it#comment_805278

## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/508970-find-the-mean-for-each-category-and-summarize-it#comment_805297

⋮## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/508970-find-the-mean-for-each-category-and-summarize-it#comment_805297

## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/508970-find-the-mean-for-each-category-and-summarize-it#comment_805317

⋮## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/508970-find-the-mean-for-each-category-and-summarize-it#comment_805317

Sign in to comment.