fill empty spaces in a cell array

15 views (last 30 days)
Mate 2u
Mate 2u on 3 Apr 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

Accepted Answer

Geoff
Geoff on 3 Apr 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 Comment
Jan
Jan on 3 Apr 2012
cellfun(@isempty, A) is faster.
cellfun('isempty', A) is fastest.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Identification 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!