Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most frequent element in a string array, MATLAB

Tags:

string

matlab

I have a string array, for instance:

arr = ['hello'; 'world'; 'hello'; 'again'; 'I----'; 'said-'; 'hello'; 'again']

How can I extract the most frequent string, which is 'hello' in this example?

like image 945
newzad Avatar asked Jul 03 '13 14:07

newzad


1 Answers

First step, use a cell array rather than string array:

arr = {'hello', 'world'; 'hello', 'again'; 'I----', 'said-'; 'hello', 'again'};

Second, use unique to get the unique strings (this doesn't work on a string array, which is why I suggest the cell):

[unique_strings, ~, string_map]=unique(arr);

Then use mode on the string_map variable to find the most common values:

most_common_string=unique_strings(mode(string_map));
like image 101
Hugh Nolan Avatar answered Oct 06 '22 23:10

Hugh Nolan