delete words from list based on logical statement
2 views (last 30 days)
Show older comments
say I have a cell array x={'abatable';'abate';'abatement';'abater';'dog';'cat';'make';'abator';'see'}
and word='abatis' letter='a'
how would I delete all words from x that do not have the letter in the respective positions of the word
For example with the letter a it appears in word abatis as the 1st letter and the 3rd letter. I would then like to delete all words from x that do not have 'a' as their 1st and 3rd positions.
I have tried this
if ismember(letter,word)
x=letter==word % returns a 1 row vector of logical statements
%.....
end
but im stuck there what else should I try.
Thanks
0 Comments
Accepted Answer
Adam Barber
on 10 Nov 2015
I slightly modified Jan's answer:
List = {'abatable';'abate';'abatement';'abater';'dog';'cat'; ...
'make';'abator';'see'}
Word = 'abatis'
C = 'a';
pattern = (Word == C);
match = false(1, numel(List));
for k = 1:numel(List)
currentWord = List{k};
lenToCheck = min(numel(pattern), numel(currentWord));
if isequal(pattern(1:lenToCheck), currentWord(1:lenToCheck) == C)
match(k) = true;
end
end
List(~match) = [];
Note that I am using the smaller of the two lengths between the words. As such, "dog" and "cat" won't work, but just the word "as" would.
Of course you could modify this to make your application work.
More Answers (2)
Jan
on 10 Nov 2015
Edited: Jan
on 12 Nov 2015
List = {'abatable';'abate';'abatement';'abater';'dog';'cat'; ...
'make';'abator';'see'}
Word = 'abatis'
C = 'a';
pattern = (Word == C);
match = false(1, numel(List));
for k = 1:numel(List)
if isequal(pattern, (List{k} == C))
match(k) = true;
end
end
List(match) = [];
[EDITED, consider word with different lengths:]
...
pattern = strfind(Word, C);
match = false(1, numel(List));
for k = 1:numel(List)
match(k) = isequal(pattern, strfind(List{k}, C))
end
List(match) = [];
In addition I've replaced the IF branching by a direct assignment.
2 Comments
Thorsten
on 12 Nov 2015
Another way would be to use strvcat
List = {'abatable';'abate';'abatement';'abater';'dog';'cat'; ...
'make';'abator';'see'}
Word = 'abatis'
C = 'a';
pattern = (Word == C);
L = strvcat(List) == 'a'; n = size(L, 2);
if length(pattern) < n, pattern(n) = 0; end
P = repmat(pattern, size(L, 1), 1);
ind = ~any(abs(P - L), 2);
List = List(ind);
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!