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

29 次查看(过去 30 天)
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 个评论
Rajiv Kumar
Rajiv Kumar 2017-3-12
if I have B = {[1 0 0 4],[0 0 0 0],[0 0 1 0],[0 0 2 3]} I want to remove zeros entries like this B = {[1 4],[],[1],[2 3]} How it is possible in cell vector
Jan
Jan 2017-3-12
编辑:Jan 2017-3-12
@Rajiv: This is a completely different question. Please do not high-jack this thread, but open a new one. Thanks.

请先登录,再进行评论。

采纳的回答

Hy
Hy 2011-1-20
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)) = [];

更多回答(4 个)

Matt Fig
Matt Fig 2011-1-20
Probably the fastest approach:
strs = strs(~cellfun('isempty',strs)) % Call Built-in string

Ned Gulley
Ned Gulley 2011-1-20
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 个评论
Jan
Jan 2011-2-1
CELLFUN(@isempty) is remarkably slower than CELLFUN('isempty') as suggested by Matt Fig.

请先登录,再进行评论。


Michael Katz
Michael Katz 2011-1-20
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 2011-2-1
For variety:
cellstr(strvcat(strs))'

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by