How to delete empty cells in a cell array?
5 views (last 30 days)
Show older comments
Matthew Tyler Jeffries
on 20 Feb 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]}
0 Comments
Accepted Answer
Walter Roberson
on 20 Feb 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 Comment
Walter Roberson
on 20 Feb 2019
arrayfun(@(IDX) {YourCell{IDX,:}}, (1:size(YourCell,1)).', 'uniform', 0)
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}
0 Comments
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))
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!