delete words from list based on logical statement

2 ビュー (過去 30 日間)
Max
Max 2015 年 11 月 10 日
回答済み: Thorsten 2015 年 11 月 12 日
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.
  1 件のコメント
Max
Max 2015 年 11 月 11 日
Is it possible to have this work for all words like dog and cat

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by