我有一个字符串数组,例如:
arr = ['hello'; 'world'; 'hello'; 'again'; 'I----'; 'said-'; 'hello'; 'again']
如何提取最常见的字符串,在这个例子中是'hello'?
第一步,使用单元数组而不是字符串数组:
arr = {'hello', 'world'; 'hello', 'again'; 'I----', 'said-'; 'hello', 'again'};
其次,使用 unique 函数可以获取唯一的字符串(这不能用于字符串数组,这就是为什么我建议使用单元格的原因):
[unique_strings, ~, string_map]=unique(arr);
然后使用 mode 函数查找 string_map 变量中出现最频繁的值:
most_common_string=unique_strings(mode(string_map));
最好使用单元数组和regexp函数;字符串数组的行为可能不符合您的预期。
arr = {'hello', 'world'; 'hello', 'again'; 'I----', 'said-'; 'hello', 'again'};
如果你使用
hellos = sum(~cellfun('isempty', regexp(arr, 'hello')));
它将返回单元数组arr
中的'hello'
数量。
regexp
会有点大材小用。strcmp
可用于识别单元数组中相等的字符串。 - kwatford
unique(arr, 'rows')
。 - Eitan Tarr
相当于['helloworld','helloagain';,'I----said-';'helloagain']
。 - Hugh Nolanarr
的错误。 - Eitan Tmost_common_string=unique_strings{mode(string_map)};
。 - Wolfie