问题
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\'
?
回答1:
I guess the following code could do the trick:
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ind=find(ismember(strs,'KU'))
This returns
ans =
2
回答2:
>> 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')
回答3:
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.
回答4:
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 :).
回答5:
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))
回答6:
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
.
回答7:
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'))
回答8:
did you try
indices = Find(strs, 'KU')
see link
alternatively,
indices = strfind(strs, 'KU');
should also work if I'm not mistaken.
来源:https://stackoverflow.com/questions/8061344/how-to-search-for-a-string-in-cell-array-in-matlab