how to get the most repeated element of a cell array?
Mostrar comentarios más antiguos
i have an cell array like this
{[];[];[];[];[];[];[];[];'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';}
is there a way to get the label of this array as rj?
3 comentarios
Cedric
el 26 de Abr. de 2013
Is the content either empty or equal to the same string? What happens if there are more empty cells than cells containing strings?
Matt J
el 26 de Abr. de 2013
maybe i did ask the question wrong, but if i have more {''} it will give me that name. instead i want {'rj'}. is there a workaround to counting?
Yes, you'll need to clarify the question. Why should {''} be ignored? Are there any other strings that should be ignored?
the cyclist
el 26 de Abr. de 2013
In other words, you need to provide a more precise definition of the rule that defines the label.
Respuesta aceptada
Más respuestas (2)
the cyclist
el 26 de Abr. de 2013
Editada: the cyclist
el 26 de Abr. de 2013
Quite convoluted, but I think this works:
cellData = {[];[];[];[];[];[];[];[];'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';'rj';}
indexToEmpty = cellfun(@isempty,cellData);
cellData(indexToEmpty) = {''};
uniqueCellData = unique(cellData);
[~,whichCell] = ismember(cellData,unique(uniqueCellData))
cellCount = hist(whichCell,unique(whichCell));
[~,indexToMaxCellCount] = max(cellCount);
maxCountElement = uniqueCellData(indexToMaxCellCount)
The essence of the algorithm is using the hist() function to count up the frequency. Unfortunately, that function only works on numeric arrays, so I had to use the ismember() command to map the cell array values to numeric values.
A further complication was the existence of the empty cell elements. I replaced them with empty strings. You'll need to be careful if your original array has empty strings.
3 comentarios
DuckDuck
el 26 de Abr. de 2013
Matt J
el 26 de Abr. de 2013
No need for ismember,
[uniqueCellData,~,whichCell] = unique(cellData);
the cyclist
el 26 de Abr. de 2013
I knew I had overlooked something easier. :-)
Peter Saxon
el 23 de En. de 2021
Editada: Peter Saxon
el 23 de En. de 2021
Found a neat solution with categories, just posting this here so when I forget how to do this and google it again I'll see it...
C = {[];[];[];[];[];[];[];[];'rj';'rj';'rj';'ab';'ab'} ;
catC=categorical(C);
catNames=categories(catC);
[~,ix] = max(countcats(catC));
disp(catName{ix}) % rj
Categorías
Más información sobre Calendar en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!