How to calculate the mean for the number of occurances

2 vues (au cours des 30 derniers jours)
johnson saldanha
johnson saldanha le 7 Déc 2018
Modifié(e) : dpb le 9 Déc 2018
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.

Réponse acceptée

dpb
dpb le 7 Déc 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 commentaires
johnson saldanha
johnson saldanha le 9 Déc 2018
all are column vectors. theres no row vector
dpb
dpb le 9 Déc 2018
Modifié(e) : dpb le 9 Déc 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by