Find multiple strings within another string

23 ビュー (過去 30 日間)
Daniel Eidsvåg
Daniel Eidsvåg 2017 年 4 月 20 日
回答済み: Tao Wang 2022 年 1 月 13 日
I am trying to find the indexes in a struct 'data.orig_reg' where the corresponding strings I am trying to find is 'a_13'. The following code works just fine.
CVT_PAT = find(~cellfun('isempty',strfind({data.orig_reg},'a_13')))';
[sharedCVTVals,~] = intersect(CVT,CVT_PAT);
If I implement multiple string searches such as:
TEST = {'a_13','a_14','a_164'}.
CVT_PAT = find(~cellfun('isempty',strfind({data.orig_reg},TEST)))';
[sharedCVTVals,~] = intersect(CVT,CVT_PAT);
This returns an error:
Error using strfind
PATTERN must be a string scalar or character vector.
This is due to strfind only takes in one string at the time as faar as I can tell... Is there a way to make this code work by using multiple strings as an input like the variable TEST described above?

採用された回答

Stephen23
Stephen23 2017 年 4 月 20 日
編集済み: Stephen23 2017 年 4 月 20 日
One solution: wrap it all up in another cellfun:
>> C = {'A','B','xxxa_13x','xxa_14x','C','a_13'};
>> TEST = {'a_13','a_14','a_164'};
>> out = cellfun(@(s)find(~cellfun('isempty',strfind(C,s))),TEST,'uni',0);
>> out{:}
ans =
3 6
ans = 4
ans = []
Note that you did not specify how you want the output: do you want to be able to distinguish which string was matched, or which pattern was matched, or both, or neither (e.g. a simple count of how many matches were made). Each of these could be coded differently.
  8 件のコメント
Stephen23
Stephen23 2017 年 4 月 21 日
編集済み: Stephen23 2017 年 4 月 21 日
Then we should use strcmp instead of strfind:
>> C = {'a_2','a_3','a_4','a_14','a_20','a_21', 'a_22'};
>> TEST = {'a_2','a_20','a_164'};
>> cellfun(@(s)find(strcmp(s,C)),TEST,'uni',0)
ans =
[1]
[5]
[]
Daniel Eidsvåg
Daniel Eidsvåg 2017 年 4 月 21 日
Thank you very much! It now works as intended =)

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

その他の回答 (1 件)

Tao Wang
Tao Wang 2022 年 1 月 13 日
mystr={'123a1','ab','111'};
pat = ("a"|"b");
a = strfind(mystr,pat)
% can get index of each match
ab = contains(mystr,pat)
% logical result

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by