Extracting strings in a cell array that contain certain characters
6 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(2 个)
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') ;
sum(c,2) % this gives the total number of letters present in each word
Stephen23
2022-3-29
W = {'gamer';'macho';'mages';'grail'};
L = 'amg';
X = cellfun(@(w)all(ismember(L,w)),W);
Z = W(X)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!