string 如何在 MATLAB 中的元胞数组中搜索字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8061344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to search for a string in cell array in MATLAB?
提问by Benjamin
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'
?
如果我想找到 的索引应该怎么做'KU'
?
回答by Vidar
I guess the following code could do the trick:
我想以下代码可以解决问题:
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ind=find(ismember(strs,'KU'))
This returns
这返回
ans =
2
回答by Pankaj Gupta
>> strs = {'HA' 'KU' 'LA' 'MA' 'TATA'};
>> tic; ind=find(ismember(strs,'KU')); toc
Elapsed time is 0.001976 seconds.
经过的时间是 0.001976 秒。
>> tic; find(strcmp('KU', strs)); toc
Elapsed time is 0.000014 seconds.
经过的时间是 0.000014 秒。
SO, clearly strcmp('KU', strs)
takes much lesser time than ismember(strs,'KU')
所以,显然strcmp('KU', strs)
比ismember(strs,'KU')
回答by Andrey Rubshtein
Since 2011a, the recommended way is:
从 2011a 开始,推荐的方式是:
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.
strfind
已弃用,所以尽量不要使用它。
回答by Curt
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:).
你不会有后顾之忧:)。
回答by robince
Other answers are probably simpler for this case, but for completeness I thought I would add the use of cellfun with an anonymous function
对于这种情况,其他答案可能更简单,但为了完整起见,我想我会添加带有匿名函数的 cellfun 的使用
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))
回答by Maxim Suslov
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
.
但它只返回 中的第一个位置strs
。如果未找到元素,则ind=0
.
回答by Andrew Janke
The strcmp and strcmpi functions are the most direct way to do this. They search through arrays.
strcmp 和 strcmpi 函数是执行此操作的最直接方法。他们搜索数组。
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ix = find(strcmp(strs, 'KU'))