MATLAB中字符串数组中最常见的元素

new*_*zad 8 string matlab

我有一个字符串数组,例如:

arr = ['hello'; 'world'; 'hello'; 'again'; 'I----'; 'said-'; 'hello'; 'again']
Run Code Online (Sandbox Code Playgroud)

如何提取最常见的字符串,'hello'在此示例中?

Hug*_*lan 13

第一步,使用单元格数组而不是字符串数组:

arr = {'hello', 'world'; 'hello', 'again'; 'I----', 'said-'; 'hello', 'again'};
Run Code Online (Sandbox Code Playgroud)

其次,使用unique来获取唯一的字符串(这不适用于字符串数组,这就是我建议单元格的原因):

[unique_strings, ~, string_map]=unique(arr);
Run Code Online (Sandbox Code Playgroud)

然后在string_map变量上使用mode来查找最常见的值:

most_common_string=unique_strings(mode(string_map));
Run Code Online (Sandbox Code Playgroud)

  • +1:但不需要单元阵列.你可以使用`unique(arr,'rows')`. (4认同)