removing elements of cell array of strings

2 visualizzazioni (ultimi 30 giorni)
how would I write a loop that removes words depending on inputs.
say I have
'aam' 'aani' 'aardvark' 'aardwolf' 'aaron' 'aaronic' 'aaronical'
If I input a random letter say "r" I would like to remove all the words that contain the letter r which would be arrdvark aardwolf aaron aaronic aaronical which leaves aam aani. Then say I input a second random letter n which removes the words with n so it would remove aani which leaves the final word aam
Thanks

Risposta accettata

per isakson
per isakson il 8 Nov 2015
Modificato: per isakson il 8 Nov 2015
One without an explicit loop
random_letter = 'r';
word_list = {'aam','aani','aardvark','aardwolf','aaron','aaronic','aaronical'};
has_r = not( cellfun( @isempty, regexp( word_list, random_letter ) ) );
word_list( has_r ) = []
outputs
word_list =
'aam' 'aani
and another with a loop
random_letter = 'r';
word_list = {'aam','aani','aardvark','aardwolf','aaron','aaronic','aaronical'};
has_r = false( 1, length( word_list ) );
for jj = 1 : length( word_list )
has_r(jj) = not( isempty( regexp( word_list{jj}, random_letter, 'once' ) ) );
end
word_list( has_r ) = []
which also outputs
word_list =
'aam' 'aani

Più risposte (0)

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by