8

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

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

如何提取最常见的字符串,'hello'在这个例子中?

4

2 回答 2

12

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));
于 2013-07-03T14:12:45.523 回答
-1

最好使用元胞数组和正则表达式函数;字符串数组的行为可能不是您所期望的。

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

如果你使用

hellos = sum(~cellfun('isempty', regexp(arr, 'hello')));

它将返回'hello'元胞数组中 's的数量arr

于 2013-07-03T14:15:24.163 回答