[string] How to search for a string in cell array in MATLAB?

Let's say I have the cell array

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}

What should I do if I want to find the index of 'KU'?

This question is related to string matlab cell-array

The answer is


The strcmp and strcmpi functions are the most direct way to do this. They search through arrays.

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ix = find(strcmp(strs, 'KU'))

did you try

indices = Find(strs, 'KU')

see link

alternatively,

indices = strfind(strs, 'KU');

should also work if I'm not mistaken.


>> strs = {'HA' 'KU' 'LA' 'MA' 'TATA'};
>> tic; ind=find(ismember(strs,'KU')); toc

Elapsed time is 0.001976 seconds.

>> tic; find(strcmp('KU', strs)); toc

Elapsed time is 0.000014 seconds.

SO, clearly strcmp('KU', strs) takes much lesser time than ismember(strs,'KU')


Since 2011a, the recommended way is:

booleanIndex = strcmp('KU', strs)

If you want to get the integer index (which you often don't need), you can use:

integerIndex = find(booleanIndex);

strfind is deprecated, so try not to use it.


Other answers are probably simpler for this case, but for completeness I thought I would add the use of cellfun with an anonymous function

indices = find(cellfun(@(x) strcmp(x,'KU'), strs))

which has the advantage that you can easily make it case insensitive or use it in cases where you have cell array of structures:

indices = find(cellfun(@(x) strcmpi(x.stringfield,'KU'), strs))

Most shortest code:

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'};
[~,ind]=ismember('KU', strs)

But it returns only first position in strs. If element not found then ind=0.


I see that everybody missed the most important flaw in your code:

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}

should be:

strs = {'HA' 'KU' 'NA' 'MA' 'TATA'} 

or

strs = {'HAKUNA' 'MATATA'}

Now if you stick to using

ind=find(ismember(strs,'KU'))

You'll have no worries :).