How do I remove the empty cells from a vector of cells?

370 views (last 30 days)
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'};
Jan on 12 Mar 2017
Edited: Jan on 12 Mar 2017
@Rajiv: This is a completely different question. Please do not high-jack this thread, but open a new one. Thanks.

Sign in to comment.

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)) = [];

More Answers (4)

Matt Fig
Matt Fig on 20 Jan 2011
Probably the fastest approach:
strs = strs(~cellfun('isempty',strs)) % Call Built-in string
Jan on 1 Feb 2011
This method is the most efficient solution.

Sign in to comment.

Ned Gulley
Ned Gulley on 20 Jan 2011
Here's one way to do it.
strs = {'one','','two','three','','','four',''};
empties = find(cellfun(@isempty,strs)); % identify the empty cells
strs(empties) = [] % remove the empty cells
This gives
strs =
'one' 'two' 'three' 'four'
  1 Comment
Jan on 1 Feb 2011
CELLFUN(@isempty) is remarkably slower than CELLFUN('isempty') as suggested by Matt Fig.

Sign in to comment.

Michael Katz
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))

Bryan White
Bryan White on 1 Feb 2011
For variety:


Community Treasure Hunt

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

Start Hunting!