How to calculate the mean for the number of occurances

2 次查看(过去 30 天)
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.

采纳的回答

dpb
dpb 2018-12-7
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 个评论
dpb
dpb 2018-12-9
编辑:dpb 2018-12-9
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by