Search code examples
matlabcell-array

Combine 2 rows in a cell array


I have a number of rows in a cell array with lots of extra space at the end of the rows as such:

'a' 'b' 'c' 'd' [] [] [] [] []
'1' '2' '3' [] [] [] [] [] []
'w' 'x' 'y' 'z' [] [] [] [] []

I would like to copy the second row onto the end of the first row, as such:

'a' 'b' 'c' 'd' '1' '2' '3' [] []
'1' '2' '3' [] [] [] [] [] []
'w' 'x' 'y' 'z' [] [] [] [] []

Please note that the code given above is an arbitrary example to demonstrate what I wish to do. In reality I will include this functionality as a step in a more complex function.

I have tried searching for the first empty element in the cell array row, but for some reason isempty does not see them as empty. Is there an alternative method that someone could point me towards?

EDIT: After the steps carried out above, the second row will be deleted, giving:

'a' 'b' 'c' 'd' '1' '2' '3' [] []
'w' 'x' 'y' 'z' [] [] [] [] []

Although the real cell array will have many more rows than 3.


Solution

  • I think this does what you want. I've denoted your cell array as c.

    n1 = find(cellfun('isempty',c(1,:)), 1); %// first empty cell in row 1
    n2 = find(cellfun('isempty',c(2,:)), 1); %// first empty cell in row 2
    c(1,n1:n1+n2-2) = c(2,1:n2-1); %// copy the relevant part of row 2 onto row 1
    

    This automatically extends your cell horizontally if the number of non-empty cells in row 2 exceeds the number of empty cells in row 1.

    Example: input:

    c = {'a' 'b' 'c' 'd' [] [] [] [] []
    '1' '2' '3' [] [] [] [] [] []
    'w' 'x' 'y' 'z' [] [] [] [] []}
    

    Output:

    c = 
        'a'    'b'    'c'    'd'    '1'    '2'    '3'    []    []
        '1'    '2'    '3'     []     []     []     []    []    []
        'w'    'x'    'y'    'z'     []     []     []    []    []