delete words from list based on logical statement

3 次查看(过去 30 天)
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

采纳的回答

Adam Barber
Adam Barber 2015-11-10
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.

更多回答(2 个)

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

请先登录,再进行评论。


Thorsten
Thorsten 2015-11-12
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);

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by