Vectorized Search of substrings in Cell Array

2 ビュー (過去 30 日間)
Timothy
Timothy 2019 年 2 月 18 日
コメント済み: Stephen23 2019 年 2 月 20 日
I have a cell array of strings and I want to match substrings to produce a boolean vector to then extract the elements of interest.
I want strfind to behave like strcmp.
t = {'abcde','bcde','abc','ac'};
i = strcmp(t,'bcde')
0 1 0 0
for example - for 'bc', I want:
1 1 1 0
but using strfind, I get :
i = strfind(t,'bc')
[2] [1] [2] []
then:
~isempty(i)
1
or:
i==[]
but this returns: 'Undefined function 'eq' for input arguments of type 'cell'.'
I think cellfun() with strfind() and isempty() might work but I'm confused how to use it.
v= cellfun(@(x) strfind(t,'bc'), t, 'UniformOutput', false)
v =
{1x4 cell} {1x4 cell} {1x4 cell} {1x4 cell}
v{1}
ans =
[2] [1] [2] []
I want boolean array: [1 1 1 0]

採用された回答

Stephen23
Stephen23 2019 年 2 月 18 日
>> t = {'abcde','bcde','abc','ac'};
>> ~cellfun(@isempty,strfind(t,'bc'))
ans =
1 1 1 0
  1 件のコメント
Timothy
Timothy 2019 年 2 月 19 日
Works brilliantly - Thanks much!

サインインしてコメントする。

その他の回答 (2 件)

the cyclist
the cyclist 2019 年 2 月 18 日
Here is one way:
cellfun(@(x)not(isempty(x)),strfind(t,'bc'))

the cyclist
the cyclist 2019 年 2 月 19 日
Discovered a much cleaner way:
contains(t,'bc');
  1 件のコメント
Stephen23
Stephen23 2019 年 2 月 20 日
Note: requires R2016b or later.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by