delete words from list based on logical statement
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Max
el 10 de Nov. de 2015
Respondida: Thorsten
el 12 de Nov. de 2015
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 comentarios
Respuesta aceptada
Adam Barber
el 10 de Nov. de 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.
Más respuestas (2)
Jan
el 10 de Nov. de 2015
Editada: Jan
el 12 de Nov. de 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 comentarios
Jan
el 12 de Nov. de 2015
@Max: Correct, the code considers words of the same length only. See EDITED.
Thorsten
el 12 de Nov. de 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 comentarios
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!