MATLAB: Filling missing elements in a matrix.

fillmissingmatrix manipulationmissing elements

Hello,
I have a matrix like this:
A = [1 0 2 0 0 2 2 2 0 2 2 2 [] [] [] [] [] ;
0 3 2 1 0 1 2 0 1 0 0 0 [] [] [] [] [] ;
0 2 3 0 2 0 1 3 0 0 0 0 [] [] [] [] [] ;
0 0 2 2 0 1 1 0 2 0 0 0 [] [] [] [] [] ;
3 0 3 0 0 0 0 1 0 1 0 1 [] [] [] [] [] ;
4 0 4 0 0 1 1 0 0 0 0 1 0 [] [] [] [] ;
0 0 3 0 0 0 0 0 0 0 0 0 0 [] [] [] [] ;
0 0 2 3 0 0 0 0 0 0 0 0 0 2 [] [] [] ;
0 0 0 3 0 1 0 0 0 0 0 [] 1 0 [] [] [] ;
4 0 0 0 3 3 1 0 0 [] 0 [] 0 0 [] 0 0 ;
0 0 0 0 2 5 1 0 0 0 0 0 0 0 [] 0 0 ;
0 0 0 0 0 1 0 0 0 0 0 0 0 0 [] 0 0 ;
0 0 2 [] 1 3 0 0 0 0 0 0 0 0 [] 0 0 ;
2 2 2 3 0 0 0 0 0 0 0 0 0 0 [] 0 0 ;
0 1 1 2 1 0 [] 0 [] 0 [] 0 [] 0 [] 0 0 ;
0 0 0 [] 0 0 0 [] 0 [] 0 [] [] 0 [] 0 0 ;
1 0 1 [] 0 0 0 0 [] 0 [] 0 [] 0 [] 0 0 ;
0 1 0 0 0 0 0 [] 0 [] 0 [] [] 0 [] 0 0 ;
[] 3 0 1 0 0 [] 0 [] 0 [] 0 0 0 [] 0 [] ;
[] [] [] [] 0 0 0 [] 0 [] 0 [] 0 0 [] 0 [] ;
[] [] [] [] 0 [] [] [] [] [] [] [] [] [] [] [] [] ;
[] [] [] 0 [] 0 0 0 [] 0 [] 0 0 0 0 [] [] ;
[] [] [] [] [] 0 0 [] 0 [] 0 [] 0 0 0 [] [] ;
[] [] [] [] 0 0 [] 0 [] 0 [] 0 0 0 [] [] [] ];
The [] denote missing elements. I want to fill in all the missing elements by holding the previous value in the same row (value to the left of the missing element) and in cases where the row begins with [] it should fill in the values from the right, again in the same row.
Please help me, I've tried the fillmissing function but it does not produce the results I am looking for.
Thanks in advance.

Best Answer

Use F = fillmissing(A,method); requires >=r2016b
Here's a demo
% Create a 20x10 cell array of integer values
% and replace 100 of the values with empties
A = num2cell(randi(9,20,10));
A(randi(numel(A),1,100)) = {[]};
% Fill empties with NaNs
A(cellfun(@isempty,A)) = {NaN};
% Convert to matrix and replace all empties with
% previous value except rows that lead with empty
F = fillmissing(cell2mat(A).','previous').';
% Replace the leftover rows the lead with empties
F = fillmissing(F.','next').';
Alternatively you could try this but in my quick tests, it didn't work so well
F = fillmissing(cell2mat(A).','previous','EndValues','next').';
If you need to convert the matrix back to a cell array (not recommended)
C = num2cell(F);