Extracting strings in a cell array that contain certain characters

4 ビュー (過去 30 日間)
Janani Guru
Janani Guru 2022 年 3 月 29 日
回答済み: Stephen23 2022 年 3 月 29 日
I have a large cell array (size undefined/changes) with each cell containing a string of five letters (words). I am trying to extract all the strings in the cell array that contain certain letters (number of letters and which letters chagnes/undefined).
For example:
words =
{'gamer'}
{'macho'}
{'mages'}
{'grail'}
letters =
'a'
'm'
'g'
and I'm trying to isolate
'gamer' and 'mages' because they contain all three letters.
The number of words in the cell array changes and the number of letters in the variable letters changes as well. Does anyone know how to go about this? I am struggling using the contains function without hard coding it. Thank you so much!

回答 (2 件)

KSSV
KSSV 2022 年 3 月 29 日
編集済み: KSSV 2022 年 3 月 29 日
There woul dbe definitely better optimal way then this.
str = [{'gamer'}
{'macho'}
{'mages'}
{'grail'}] ;
letters = {'a' 'm' 'g'} ;
str = reshape(cellstr([str{:}]'),5,[])' ; % there could be another optimal way for this
[c,ia] = ismember(str,letters,'row') ;
Warning: The 'rows' input is not supported for cell array inputs.
sum(c,2) % this gives the total number of letters present in each word
ans = 4×1
3 2 3 2
  1 件のコメント
Janani Guru
Janani Guru 2022 年 3 月 29 日
I'm sorry I'm not very proficient in Matlab so pardon the poor question, but what am I supposed to do with the logical matrix c?

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


Stephen23
Stephen23 2022 年 3 月 29 日
W = {'gamer';'macho';'mages';'grail'};
L = 'amg';
X = cellfun(@(w)all(ismember(L,w)),W);
Z = W(X)
Z = 2×1 cell array
{'gamer'} {'mages'}

カテゴリ

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