8

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?

2 Answers 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));
Sign up to request clarification or add additional context in comments.

6 Comments

+1: but there's no need for cell arrays. You can use unique(arr, 'rows').
Oh great, thanks! I don't use them very often, didn't know this function.
Just a note about string arrays and the above comment: in this instance, the string would need to be reformatted so that each string was a separate row, rather than trying to have two strings on a single line - this only works as a cell, otherwise Matlab considers the whole line a single concatenated string, i.e. the initial arr in the question is equivalent to ['helloworld','helloagain';,'I----said-';'helloagain']
All strings in the question are concatenated vertically with a semicolon. I think you copy-pasted arr wrong.
Oh weird. Thanks. Don't know how that happened.
|
-1

It is better to use cell arrays and regexp function; the behavior of string arrays may not be what you expect.

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

If you use

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

it will return the number of 'hello''s in cell array arr.

2 Comments

-1: The question is about finding the most frequent string, not a specific predetermined string.
And even if you were looking for a specific string, regexp would be a bit overkill. strcmp can be used to identify equal strings in a cell array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.