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

23 visualizaciones (últimos 30 días)
Ned Gulley
Ned Gulley el 20 de En. de 2011
Editada: Jan el 12 de Mzo. de 2017
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 comentarios
Rajiv Kumar
Rajiv Kumar el 12 de Mzo. de 2017
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 el 12 de Mzo. de 2017
Editada: Jan el 12 de Mzo. de 2017
@Rajiv: This is a completely different question. Please do not high-jack this thread, but open a new one. Thanks.

Iniciar sesión para comentar.

Respuesta aceptada

Hy
Hy el 20 de En. de 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)) = [];

Más respuestas (4)

Matt Fig
Matt Fig el 20 de En. de 2011
Probably the fastest approach:
strs = strs(~cellfun('isempty',strs)) % Call Built-in string
  2 comentarios
Jan
Jan el 21 de En. de 2011
Or the other way around:
strs(cellfun('isempty',strs)) = []
Jan
Jan el 1 de Feb. de 2011
This method is the most efficient solution.

Iniciar sesión para comentar.


Ned Gulley
Ned Gulley el 20 de En. de 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 comentario
Jan
Jan el 1 de Feb. de 2011
CELLFUN(@isempty) is remarkably slower than CELLFUN('isempty') as suggested by Matt Fig.

Iniciar sesión para comentar.


Michael Katz
Michael Katz el 20 de En. de 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 el 1 de Feb. de 2011
For variety:
cellstr(strvcat(strs))'

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by