How do I remove the empty cells from a vector of cells?
370 views (last 30 days)
Show older comments
I have a vector of cells which contain strings. Some of the cells in the vector are empty. I want to remove the empty cells from the vector.
Suppose I start with
strs = {'one','','two','three','','','four',''};
and I want to end with
strs = {'one','two','three','four'};
2 Comments
Accepted Answer
Hy
on 20 Jan 2011
The built-in function strcmp can compare a character array to a cell array of strings. Matching cells may be removed by setting them equal to the empty array.
strs(strcmp('',strs)) = [];
0 Comments
More Answers (4)
Matt Fig
on 20 Jan 2011
Probably the fastest approach:
strs = strs(~cellfun('isempty',strs)) % Call Built-in string
2 Comments
Ned Gulley
on 20 Jan 2011
1 Comment
Jan
on 1 Feb 2011
CELLFUN(@isempty) is remarkably slower than CELLFUN('isempty') as suggested by Matt Fig.
Michael Katz
on 20 Jan 2011
I wanted to do:
strs = setdiff(strs,{''})
but turns out it reorders the output:
strs =
'four' 'one' 'three' 'two'
So, I wound up with this:
[~,ix] = setdiff(strs,{''})
strs = strs(sort(ix))
0 Comments
See Also
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!