Borrar filtros
Borrar filtros

How to calculate the mean for the number of occurances

2 visualizaciones (últimos 30 días)
johnson saldanha
johnson saldanha el 7 de Dic. de 2018
Editada: dpb el 9 de Dic. de 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.

Respuesta aceptada

dpb
dpb el 7 de Dic. de 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 comentarios
johnson saldanha
johnson saldanha el 9 de Dic. de 2018
all are column vectors. theres no row vector
dpb
dpb el 9 de Dic. de 2018
Editada: dpb el 9 de Dic. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by