How to delete empty cells in a cell array?
Show older comments
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]}
Accepted Answer
More Answers (2)
Peter Perkins
on 21 Feb 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
on 22 Feb 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))
Categories
Find more on Numeric Types in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!