fill empty spaces in a cell array

16 vues (au cours des 30 derniers jours)
Mate 2u
Mate 2u le 3 Avr 2012
Hi all, I have a 2000x2 cell array.
When I go down I see some rows have [] [] empty. What way can I do it so that the empty 2 cells in the array are always replaced by the next immediate rows underneath it?
I hope this was easy to understand:
Eg,
123341 23.123
324523 34.245
[] []
234536 23.452
Then my output would be:
123341 23.123
324523 34.245
234536 23.452
234536 23.452

Réponse acceptée

Geoff
Geoff le 3 Avr 2012
Here's a clunky solution:
function [A] = FillEmptyRows( A )
while 1
emptyCells = cellfun(@(x) isempty(x), A);
emptyRows = all(emptyCells,2);
if ~any(emptyRows)
break;
end
nextRows = circshift(emptyRows,1);
A(emptyRows,:) = A(nextRows,:);
end
end
It works by identifying rows that are entirely empty (so a row with only one empty entry won't be replaced), and replaces that with the next row.
For simplicity, I use circshift to use the logical index on the next row, but that means if your last row is empty it will be replaced by the first row.
If you have multiple consecutive empty rows, the loop will go round several times but you'll always end up with a filled result. Don't call it if EVERY row is empty.
  1 commentaire
Jan
Jan le 3 Avr 2012
cellfun(@isempty, A) is faster.
cellfun('isempty', A) is fastest.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by