How to calculate the mean for the number of occurances

2 views (last 30 days)
suppose i have a cell C where
C{1,1}= ( 2 2 2 2 3 3 4 4 5);
C{2,1}=(3 4 4 4 5);
C{3,1}=(4 5);
and so on
i want the output as
x = (2 2 2 2 3 3 4 4 5);
the output should be the value which occurs the mean number of times of the occurances in the input. if the value is a decimal then it can rounded to a greater whole number for ex: the value 3 occurs twice in first cell and once in second cell. 2+1/2= 1.5 can be rounded to 2. so it occurs twice in the output.

Accepted Answer

dpb
dpb on 7 Dec 2018
u=unique([C{:}]);
n=cell2mat(cellfun(@(x) histc(x,u),C,'uni',0));
n(n==0)=nan;
x=cell2mat(arrayfun(@(x,n) repmat(x,1,n),u,round(nanmean(n)),'uni',0));
>> x =
2 2 2 2 3 3 4 4 5
>>
  9 Comments
dpb
dpb on 9 Dec 2018
Edited: dpb on 9 Dec 2018
That's not what the error message says... :)
If the vectors inside the initial cell array are columns instead of rows as your initial example, then as above you'll have to first cat(1,...) them, but then the counts array will end up being a column vector instead of the 2D array because cellfun will just concatenate those columns into one long (column) vector instead of concatenating the rows vertically and you've thus lost the orientation that lets nanmean know how to average across the cells as is the whole end objective.
Probably the easiest way to code it would be to transpose the argument of the histc function inside the anonymous function so it is again a row vector there as needs must be...otherwise, you've got much more painful gyrations to build the necessary array shape.
Step through each step at the command line for a (smallish) example so you can see the results of each operation and get the proper orientation for the job.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!