How to delete empty cells in a cell array?

5 visualizaciones (últimos 30 días)
Matthew Tyler Jeffries
Matthew Tyler Jeffries el 20 de Feb. de 2019
Respondida: Stephen23 el 22 de Feb. de 2019
I would like to delete all of the empty {0×0 double} cells in each row, then shift the cells that have values in them to the left.
Starting with:
{["laterite-00001"]} {[ 30552]} {[ 227634]} {[ 123220]}
{["laterite-00002"]} {0×0 double} {0×0 double} {[1345]}
{["laterite-00003"]} {0×0 double} {0×0 double} {[443266]}
{["laterite-00004"]} {0×0 double} {0×0 double} {[87887]}
{["laterite-00005"]} {[1323]} {[87455]} {[23345]}
{["laterite-00006"]} {[43233]} {[454547]} {0×0 double}
I would like to end with this:
{["laterite-00001"]} {[30552]} {[227634]} {[123220]}
{["laterite-00002"]} {[1345]}
{["laterite-00003"]} {[443266]}
{["laterite-00004"]} {[87887]}
{["laterite-00005"]} {[1323]} {[87455]} {[23345]}
{["laterite-00006"]} {[43233]} {[454547]}

Respuesta aceptada

Walter Roberson
Walter Roberson el 20 de Feb. de 2019
What you show us for input is a 6 x 4 cell array, some entries of which happen to contain empty arrays.
What you show us for desired output is something that does not exist in MATLAB: a rectangular cell array with "holes". Some people refer to this as a "ragged" array.
The closest you can get in MATLAB is that you could make a 6 x 1 cell array, each entry of which was a cell array:
{{"laterite-00001" 30552 227634 123220}
{"laterite-00002" 1345}
...
}
  1 comentario
Walter Roberson
Walter Roberson el 20 de Feb. de 2019
arrayfun(@(IDX) {YourCell{IDX,:}}, (1:size(YourCell,1)).', 'uniform', 0)

Iniciar sesión para comentar.

Más respuestas (2)

Peter Perkins
Peter Perkins el 21 de Feb. de 2019
Another alternative, which may not be what you are looking for:
>> c = {11 12 13; 21 [] 23; 31 [] []}
c =
3×3 cell array
{[11]} {[ 12]} {[ 13]}
{[21]} {0×0 double} {[ 23]}
{[31]} {[ 32]} {0×0 double}
>> for i = 1:size(c,1)
j = ~cellfun('isempty',c(i,:));
numNotEmpty = sum(j);
cc = repmat({missing},1,size(c,2));
cc(1,1:numNotEmpty) = c(i,j);
c(i,:) = cc;
end
>> c
c =
3×3 cell array
{[11]} {[12]} {[ 13]}
{[21]} {[23]} {1×1 missing}
{[31]} {[32]} {1×1 missing}

Stephen23
Stephen23 el 22 de Feb. de 2019
Shifts the empty cell to the right, without any explicit loops:
c = {11,12,13;21,[],23;31,[],[]}
[~,idc] = sort(cellfun(@isempty,c),2)
s = size(c);
[idr,~] = ndgrid(1:s(1),1:s(2));
c = c(sub2ind(s,idr,idc))

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by