Searching word list for key letters
1 view (last 30 days)
Show older comments
user86753
on 24 Jan 2022
Commented: Walter Roberson
on 24 Jan 2022
wordList = {'apples'
'orange'
'banana'};
ContainList = 'shu';
NotContainList = 'br';
I'd like to be able to find all words that contain the letters S,H or U and do not have the letters B or R. I'm using 'contains' for each letter but is there a way to loop through the ContainList/NotContainList for each word?
0 Comments
Accepted Answer
Walter Roberson
on 24 Jan 2022
Edited: Walter Roberson
on 24 Jan 2022
wordList = {'apples'
'orange'
'banana'};
ContainList = 'shu';
NotContainList = 'br';
mask1 = contains(wordList, num2cell(ContainList))
mask2 = contains(wordList, num2cell(NotContainList))
filtered_words = wordList(mask1 & ~mask2)
%another approach
mask3 = ~cellfun(@isempty, regexp(wordList, "[" + ContainList + "]"))
mask4 = ~cellfun(@isempty, regexp(wordList, "[" + NotContainList + "]"))
filtered_words2 = wordList(mask3 & ~mask4)
%another approach
pattern = "^[^" + NotContainList + ContainList + "]*[" + ContainList + "][^" + NotContainList + "]*$"
mask5 = ~cellfun(@isempty, regexp(wordList, pattern))
filtered_words3 = wordList(mask5)
1 Comment
Walter Roberson
on 24 Jan 2022
In some cases you might want to work iteratively
wordList = {'apples'
'orange'
'banana'};
ContainList = 'shu';
NotContainList = 'br';
words_containing = wordList(contains(wordList, num2cell(ContainList)));
filtered_words = words_containing(~contains(wordList, num2cell(NotContainList)));
In situations where you are doing stepwise refinement, it is most efficient to start from the steps that are expected to make the most difference, each step discarding as much as practical, so that each step is searching less and less information.
More Answers (1)
David Hill
on 24 Jan 2022
wordList = {'apples','orange','banana','show','unit'};
ContainList = 'shu';
NotContainList = 'br';
r=wordList(contains(wordList,num2cell(ContainList))&~contains(wordList,num2cell(NotContainList)));
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!