Search code examples
matlabcell-arraymode

Most frequent string in cell array without respecting the alphabetical order


I want to find the most common string in a cell array but without respecting the alphabetical order. Let me explain better with an example.

If I have this:

list = {'car', 'glasses', 'glasses', 'apple', 'apple'};

I want the answer to be glasses and not apple because glasses comes before apple in the array, even if apple is alphabetically less than glasses.

This method works but returns apple:

[unique_strings, ~, string_map] = unique(list);
mostComm = unique_strings(mode(string_map)); % -> apple

Solution

  • Use 'stable' option with unique to keep the order -

    [unique_strings, ~, string_map] = unique(list,'stable');
    unique_strings(mode(string_map))
    

    From docs :

    [C,ia,ic] = unique(A,setOrder) and [C,ia,ic] = unique(A,'rows',setOrder) return C in a specific order. setOrder can be 'sorted' or 'stable':

    'stable' — C is in the same order as A.

    Sample run -

    >> list
    list = 
        'car'    'glasses'    'glasses'    'apple'    'apple'
    >> [unique_strings, ~, string_map] = unique(list,'stable');
    >> unique_strings(mode(string_map))
    ans = 
        'glasses'