delete words from list based on logical statement

2 views (last 30 days)
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

Accepted Answer

Adam Barber
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.
  1 Comment
Max
Max on 11 Nov 2015
Is it possible to have this work for all words like dog and cat

Sign in to comment.

More Answers (2)

Jan
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
Max
Max on 10 Nov 2015
When I type that in it returns List={'abatable';'abate';'abatement';'dog';'cat';'make';'see'}
Jan
Jan on 12 Nov 2015
@Max: Correct, the code considers words of the same length only. See EDITED.

Sign in to comment.


Thorsten
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);

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!