removing elements of cell array

16 views (last 30 days)
James Connor
James Connor on 9 Nov 2015
Edited: William Smith on 3 Apr 2018
say I have a 1 column cell array
and word=nanny
how would I remove all words from the cell array that are not equal length to the word. For example. length(word)=5
remove all words from x that are not length 5

Answers (2)

Stephen23 on 9 Nov 2015
>> x = {'aa';'aal';'aalii';'aam';'aani';'aardvark';'aardwolf';'aaron'};
>> word = 'nanny';
>> x(numel(word)~=cellfun(@numel,x)) = []
x =
Use your favorite internet search engine to locate the official MATLAB documentation for the functions that I used. MATLAB has really great documentation, and you will be doing yourself a great favor by learning to use it.

William Smith
William Smith on 3 Apr 2018
Edited: William Smith on 3 Apr 2018
If it's just explicit items you want to remove, rather based on a function, you can simply use 'setdiff'.
setdiff({'one', 'two', 'buckle', 'my', 'shoe'},{'boot', 'my', 'shoe'})
ans =
1×3 cell array
'buckle' 'one' 'two'

Community Treasure Hunt

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

Start Hunting!