How to search for a string in cell array in MATLAB?
StringMatlabCell ArrayString Problem Overview
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'
?
String Solutions
Solution 1 - String
I guess the following code could do the trick:
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ind=find(ismember(strs,'KU'))
This returns
ans =
2
Solution 2 - String
>> 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')
Solution 3 - String
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.
Solution 4 - String
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][2] :).
[2]: http://en.wikipedia.org/wiki/Hakuna_matata "I always thought Disney just made up hakuna matata, but it's actually Swahilli for "no worries" "
Solution 5 - String
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))
Solution 6 - String
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
.
Solution 7 - String
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'))
Solution 8 - String
did you try
indices = Find(strs, 'KU')
see link
alternatively,
indices = strfind(strs, 'KU');
should also work if I'm not mistaken.