How to delete empty cells in a cell array?
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Matthew Tyler Jeffries
am 20 Feb. 2019
Beantwortet: Stephen23
am 22 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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 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 Kommentar
Walter Roberson
am 20 Feb. 2019
arrayfun(@(IDX) {YourCell{IDX,:}}, (1:size(YourCell,1)).', 'uniform', 0)
Weitere Antworten (2)
Peter Perkins
am 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 Kommentare
Stephen23
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!