removing elements of cell array of strings

조회 수: 2 (최근 30일)
Max
Max 2015년 11월 8일
편집: per isakson 2015년 11월 8일
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

채택된 답변

per isakson
per isakson 2015년 11월 8일
편집: per isakson 2015년 11월 8일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by