MATLAB: Merge cell arrays by row

cell arraystring

Hello,
I'm trying to filter a cell array which contains data in the form of strings. Every cell element can have a non-uniform length. For example:
c = {'a', 'b', 'c';
'', 'd', 'e';
'', 'f', 'g';
'h', 'i', 'j';
'k', '', ''};
For the sake of this example, all cells have length 1, which is not the case in a real scenario.
Say that the first column contains descriptions, and the other columns contain data. Thus, if the first column has empty strings, the rows should be added to the row above. If both the second and the third column have empty strings, while the first one has not, the same should happen.
So, the output should be:
c2 = {'a','bdf','ceg';
'hk','i','j'}
Of course, I want to achieve this with one command, if possible (no for loops), but I can't figure out a good solution. Detection of rows that should be combined isn't that hard, for example:
s = cellfun(@isempty, c);
emptyRows = all(s(:,1:metaCols),2) | all(s(:,metaCols+1:end),2); % result: [0 1 1 0 1].'
keepRows = diff([emptyRows; 0]) == 1; % result: [1 0 0 1 0].'
Where metaCols = 1 in this case.
The question is, how to concatenate the cell strings from partially empty rows into the cell strings of the above row? I have the feeling this should be possible without for loops (and cellfun/arrayfun).
One solution could be to shift the rows that are to be concatenated to a 3rd dimension, but I don't know how to do that.
Thanks in advance!

Best Answer

c = {'a', 'b', 'c';
'', 'd', 'e';
'', 'f', 'g';
'h', 'i', 'j';
'k', '', ''};
n = cumsum(all(~cellfun(@isempty,c),2));
[ii,jj] = ndgrid(n,1:size(c,2));
c2 = accumarray([ii(:),jj(:)],(1:numel(c))',[],@(x){[c{x}]});